如何在这里应用java ExecutorService和Executors类

时间:2013-04-12 00:02:25

标签: java multithreading threadpool

我想在选项2中使用线程池来替换选项1中的代码。我该如何实现? 1
    1.使用Join

Thread e1 = new Thread(new EventThread("e1"));
e1.start();
Thread e2 = new Thread(new EventThread("e2"));
e2.start();

 e1.join();
 e2.join();

 // from here 'main' thread continue

2.使用线程池 现在我想使用ExecutorService类

执行相同的工作
public class EventThread implements Runnable{
   public EventThread(String message){
   }
} 

ExecutorService executor = Executors.newFixedThreadPool(2);

Runnable worker = new EventThread("");
executor.execute(worker);


executor.shutdown();
while (!executor.isTerminated()) {

}
System.out.println("Finished all threads"); 

//从这里'主'线程继续

这与第一个完全相同吗?或者我的代码是对的? 谢谢。

2 个答案:

答案 0 :(得分:2)

没有。功能上唯一的区别是在选项2中只有一个线程在执行。您仍然需要向其添加每个工作程序,Fixed size只是可以并发运行的最大线程数量(如果添加第三个线程,它将等待一个先前添加的线程完成后再运行它) 。

此外,不推荐繁忙的等待(具有条件!executor.isTerminated()的while循环),这是不好的做法。相反,我建议使用executor.awaitTermination(long timeout, TimeUnit unit)或至少在循环中使用Thread.sleep()

答案 1 :(得分:0)

在您的第一个示例中,您将运行2个线程,但在第二个示例中,即使您拥有2个线程的线程池,您也只能运行1个runnable。所以不会使用池中的第二个线程。

您也可以在关机后使用awaitTermination()而不是while循环:

ExecutorService executor = Executors.newFixedThreadPool(2);
for(i=0;i<2;i++){
  executor.execute(new EventThread("e"+i));
}
executor.shutdown();
try {
  executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
  ...
}
System.out.println("Finished all threads"); 
相关问题