Java 计划执行器服务等待所有线程完成
Java Scheduled Executor Service wait all threads complete
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..请帮忙,谢谢!
而不是
if (scheduleAtFixedRate != null)
{
while(!scheduleAtFixedRate.isDone())
//wait...
}
在您的 Runnable class 中添加一个 volatile 变量,如下所示。
public volatile boolean isRunning = false;
一旦您的线程完成工作,将其更改为 true 并在您的检查部分中输入 .
while(!autoUpdate.isRunning);
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..请帮忙,谢谢!
而不是
if (scheduleAtFixedRate != null)
{
while(!scheduleAtFixedRate.isDone())
//wait...
}
在您的 Runnable class 中添加一个 volatile 变量,如下所示。
public volatile boolean isRunning = false;
一旦您的线程完成工作,将其更改为 true 并在您的检查部分中输入 .
while(!autoUpdate.isRunning);