2013-05-02 104 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