2016-08-09 83 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. 
*/