在我的应用程序中,我有两个 jtextpane,并且有一个 executorservice instacne,其中包含很少的任务。我想确保在执行任何 jtextpanes 的 FocusListener focusGained 方法之前,executorservice 实例中的所有任务都已完成。另外,当调用 focusLost 方法时,我向 executorservice 添加了更多任务。
代码
top.addFocusListener(new FocusListener()
{
public void focusLost(FocusEvent e)
{
if (ecaViewControl.isInitialized())
{
stopRecording();
executor.execute(new Runnable()
{
public void run()
{
ecaViewControl.save(top);
}
});
executor.execute(new Runnable()
{
public void run()
{
ecaViewControl.closeDocument();
}
});
}
}
public void focusGained(FocusEvent e)
{
//Need to have completed all the task in executor service before EDT executes the code in here
});
}
最佳答案
如果您确实知道要完成的任务数量,请考虑使用 CountDownLatch
所以你的代码可能看起来像:
public void run() {
try {
// do something here
} finally {
latch.countDown()
}
}
然后在等待任务完成的代码中 - 只需等待闩锁:
latch.await();
或者,使用 CompletionService如果您可以在没有遗嘱执行人的情况下生活。
关于java - 阻止 EDT 直到 executorservice 完成所有任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12460214/