2016-08-09 81 views
-1

我想運行一個任務,該任務包含一個執行其他任務的Timer。我需要等到這個子任務完成執行後才能運行另一個「父任務」。Java多線程 - 每次任務完成任務時調度任務

那麼如何讓主要任務等到其子任務完成執行後再拍攝另一個任務?

我想在每個任務與布爾isDone通知,但林不知道,如果它的正確

+0

請提供的代碼示例:http://stackoverflow.com/help/how-to-ask –

+0

如果你提交任務,你會得到一個'未來',你可以把它放到一個列表中。然後你可以調用'get()'來完成每個返回的操作。 – Fildor

回答

0

您可以在父線程使用CountDownLatch這將等到孩子完成它的工作,並調用倒計時()方法,以便父線程可以繼續工作。你可以有多個孩子,你可以調整CountDownLatch的計數值與它們相等。

我不會推薦使用volatile變量,因爲您必須連續將父線程置於睡眠狀態並檢查變量是否在喚醒後發生了更改。

0

等待一堆任務的完成:invokeAll

// Assume we have an ExecutorService "pool" and tl is list of tasks 
List<Future<SomeType>> results = pool.invokeAll(tl); // will block until all tasks in tl are completed 

或者

// Assume we have an ExecutorService "pool" and N is the count of tasks 
List<Future<SomeType>> batch = new ArrayList<>(N); 

for(int i = 0; i < N; i++){ 
    batch.add(pool.submit(new Task(i))); 
} 

for(Future fut : batch) fut.get(); 
/* get will block until the task is done. 
* If it is already done it will return immediately. 
* So if all futures in the list return from get, all tasks are done. 
*/