在Java中要运行多少个线程? [英] how many threads to run in java?
问题描述
我有一个绝妙的主意,可以加快生成36个文件所需的时间:使用36个线程!不幸的是,如果我使用36个线程/会话启动一个连接(一个j2ssh
连接对象),则与每次执行每个线程相比,所有事情的滞后时间都更大.
现在,如果我尝试创建36个新连接(36个j2ssh
连接对象),则每个线程都具有到服务器的单独连接,要么我内存不足异常(以某种方式程序仍然运行,并成功结束其工作,但速度比我一个接一个执行另一个线程的时间).
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).
那该怎么办?如何找到我应该使用的最佳线程号?
因为Thread.activeCount()
在启动我的36个线程之前是3?我正在使用联想笔记本电脑英特尔酷睿i5.
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.
推荐答案
您可以使用ExecutorService
将其范围缩小到更合理的线程数.您可能想使用接近可用处理器核心数量的东西,例如:
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();
这篇关于在Java中要运行多少个线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!