2013-11-01 50 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)将需要很长时间我担心线程队列将过载和内存资源将被耗尽。

是否值得关注?