java多少个线程在执行,在Java中要运行多少个线程?

博主探讨了尝试使用36个线程同时生成36个文件以提高效率,但发现这导致性能下降甚至出现内存溢出。解决方案是通过ExecutorService创建与处理器核心数相匹配的固定线程池,从而实现更有效的并行处理,降低了系统资源的消耗。

I had this brilliant idea to speed up the time needed for generating 36 files: use 36 threads!! Unfortunately if I start one connection (one j2ssh connection object) with 36 threads/sessions, everything lags way more than if I execute each thread at a time.

Now if I try to create 36 new connections (36 j2ssh connection objects) then each thread has a separate connection to server, either i get out of memory exception (somehow the program still runs, and successfully ends its work, slower than the time when I execute one thread after another).

So what to do? how to find the optimal thread number I should use?

because Thread.activeCount() is 3 before starting mine 36 threads?! i'm using Lenovo laptop Intel core i5.

解决方案

You could narrow it down to a more reasonable number of threads with an ExecutorService. You probably want to use something near the number of processor cores available, e.g:

int threads = Runtime.getRuntime().availableProcessors();

ExecutorService service = Executors.newFixedThreadPool(threads);

for (int i = 0; i < 36; i++) {

service.execute(new Runnable() {

public void run() {

// do what you need per file here

}

});

}

service.shutdown();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值