有一个带有单个线程的线程池,用于执行多个线程提交的任务。该任务实际上由两部分组成 - 具有有意义结果的执行
和需要相当长的时间但不返回任何有意义结果的清理
。目前(显然不正确)的实现看起来像这样。有没有一种优雅的方法来确保另一个 perform
任务仅在上一个 cleanup
任务之后执行?
public class Main {
private static class Worker {
int perform() {
return 1;
}
void cleanup() {
}
}
private static void perform() throws InterruptedException, ExecutionException {
ExecutorService pool = Executors.newFixedThreadPool(1);
Worker w = new Worker();
Future f = pool.submit(() -> w.perform());
pool.submit(w::cleanup);
int x = (int) f.get();
System.out.println(x);
}
}
最佳答案
Is there an elegant way to ensure that another perform task will be executed only after previous cleanup task?
最明显的事情是从 perform()
调用 cleanup()
但我认为你不这样做是有原因的。
您说您的解决方案目前“明显不正确”。为什么?因为竞争条件?然后你可以添加一个synchronized
block :
synchronized (pool) {
Future f = pool.submit(() -> w.perform());
pool.submit(w::cleanup);
}
这将确保 cleanup()
在 perform()
之后立即执行。如果您担心同步
对性能造成影响,请不要担心。
另一个解决方案可能是使用 ExecutorCompletionService
class虽然我不确定这对一个线程有什么帮助。我以前在另一个线程池中运行清理任务时使用过它。
关于java - 连续执行两个任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38610505/