我遇到了一个问题,我希望你的大师可以帮忙。限制产生的线程数
我正在设计一个多线程的Java应用程序,我想在任何时候将产生的线程数限制为5。 main()程序应暂停,并等待池中的线程可用,直到恢复其进程。
目前这里是我想出来的,但似乎我检测活动线程的数量的方式不是很准确。
只是想知道是否有另一种方式来做到这一点。
ExecutorService pool = Executors.newFixedThreadPool(5);
for(int i=0; i<10000; i++){
System.out.println("current number of threads: "+((ThreadPoolExecutor)pool).getActiveCount());
while(true){
if (((ThreadPoolExecutor)pool).getActiveCount() < 5)
break;
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
System.out.println("waiting ..... "+((ThreadPoolExecutor)pool).getActiveCount());
}
Runnable sampleThread = new SampleThread(100);
pool.submit(sampleThread);
}
**************************************************
** Output:
**************************************************
current number of threads: 0
current number of threads: 1
current number of threads: 1
current number of threads: 1
current number of threads: 1
有没有另一种方法来实现我想要做的? 我做了一些研究,没有什么比较适合这项法案。
由于事先 爱德蒙
“pool”在任何时候都不会有超过5个活动线程。什么是关心? –
你是什么意思,他们不是很准确? – 2013-11-01 18:43:32
为什么你不能继续提交任务并让Executor处理它。 –