Java Scheduled Executor Service等待所有线程完成

时间:2015-01-14 09:07:27

标签: java service executor

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(4);
for (int i = 0; i < 4; i++)
{Runnable autoUpdate = new autoUpdateWork(i);
ScheduledFuture<?> scheduleAtFixedRate = scheduler.scheduleAtFixedRate(autoUpdate, 0, 60, TimeUnit.SECONDS);
}
if (scheduleAtFixedRate != null)
    {    
        while(!scheduleAtFixedRate.isDone())
        //wait...
    }
//PointA :until all threads are finished, do sth, then invoke the scheduled task with 60 sec interval    again.

到目前为止,上面是我的代码。但似乎它永远不会到达PointA ..请帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

而不是

if (scheduleAtFixedRate != null)
{    
    while(!scheduleAtFixedRate.isDone())
    //wait...
}

在Runnable类中添加一个volatile变量,如下所示。

public  volatile boolean isRunning = false;

一旦你的线程完成了工作,将其更改为true,并在你的检查部分中添加。

while(!autoUpdate.isRunning);