2013-05-02 105 views
1

我使用ExecutorService执行了n个Runnable任务(不是Callable)。等待完成ExecutorService中Runnable任务的有效方法

我想等待所有任务完成。我不能使用invokeAll - 因为它适用于收集可卡因。

我不能使用shutdown()+awaitTermination,因为候诊需要提供暂停,但我的任务可能需要几小时才能完成。

我可以使用:

ExecutorService.shutdown();    
while (!ExecutorService.isTerminated()) {} 

但这个循环将始终触发。

这种情况下有什么建议?

回答

2

您可以使用ExecutorService.awaitTermination(Long.MAX_VALUE, TimeUnit.HOURS);

+0

在我的文章中,我特别写了为什么我不能使用它。 – yuris 2013-05-02 06:35:13

+0

对,修正了我的答案 – 2013-05-02 06:43:58

+0

在我的Java版本中,TimeUnit没有HOUR或DAY – yuris 2013-05-02 06:51:27

4

ExecutorService.awaitTermination()返回boolean这表明,如果执行终止或暂停时间已过。你可以ofcourse把它在一个循环:

ExecutorService executor = ...; 

executor.shutdown(); 
while (!executor.awaitTermination(24L, TimeUnit.HOURS)) { 
    System.out.println("Still waiting for the executor to finish"); 
} 

System.out.println("Executor finished"); 
1

对于已知数量的任务CountDownLatch仅仅是完美的,但有这样的情况,当你不知道你将有多少任务,在这种情况下我使用Semaphore 。例如:

Semaphore s =new Semaphore(0); 
    while(..){ 
    if (isLastTask){ 
     taskExecutor.execute(new Task(s)); 
    } else 
     taskExecutor.execute(new Task()); 
    } 
    s.acquire(1); 

class Task implement implements Runnable { 
    Semaphore s; 

    public Task(){ 
    this(null); 
    } 

    public Task (Semaphore s){ 
    this.s = s; 
    } 

    public void run(){ 
     ...... 
     if (s != null) 
      s.release(); 
    } 
} 
+0

while循环必须在类之前关闭宣言。 – KrishPrabakar 2015-12-30 10:27:16