我遇到了一個問題,我希望你的大師可以幫忙。限制產生的線程數
我正在設計一個多線程的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處理它。 –