2013-11-01 51 views
0

我遇到了一個問題,我希望你的大師可以幫忙。限制產生的線程數

我正在設計一個多線程的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 

有沒有另一種方法來實現我想要做的? 我做了一些研究,沒有什麼比較適合這項法案。

由於事先 愛德蒙

+1

「pool」在任何時候都不會有超過5個活動線程。什麼是關心? –

+0

你是什麼意思,他們不是很準確? – 2013-11-01 18:43:32

+0

爲什麼你不能繼續提交任務並讓Executor處理它。 –

回答

1

您從java.util.concurrent.Executors這是的newFixedThreadPool - 它已位於限制5個線程。你確定它沒有被限制到5個線程嗎?

+0

OP已經在使用'newFixedThreadPool'。 –

+0

那就是我說的 - 重新編寫它 – Voidpaw

+0

我在第一條評論中的含義是強調CAN,如下所示:代碼沒有任何問題。 – Voidpaw

1

如果不知道SampleThread是什麼,很難回答。如果它沒有耗費時間,則線程可能在循環繼續之前完成。例如

public static class SampleThread implements Runnable { 
    @Override 
    public void run() { 
    } 

} 

回報

current number of threads: 0 
current number of threads: 0 
current number of threads: 0 
current number of threads: 0 
current number of threads: 0 
current number of threads: 0 
current number of threads: 0 

public static class SampleThread implements Runnable { 
    @Override 
    public void run() { 
     try { 
      Thread.sleep(100); 
     } catch (InterruptedException e) { 
      System.out.println(e); 
     } 
    } 
} 

回報

current number of threads: 0 
current number of threads: 1 
current number of threads: 2 
current number of threads: 3 
current number of threads: 4 
current number of threads: 5 
waiting ..... 0 
current number of threads: 0 
current number of threads: 1 
current number of threads: 2 
current number of threads: 3 
current number of threads: 4 
current number of threads: 5 
waiting ..... 0 

您可以編輯用什麼SampleThread做信息的帖子?

0

謝謝你們,示例線程負責發送電子郵件通知給我的客戶。

由於發送電子郵件(高達100)將需要很長時間我擔心線程隊列將過載和內存資源將被耗盡。

是否值得關注?