【发布时间】:2016-07-27 10:33:31
【问题描述】:
有一个带有单个线程的线程池,用于执行由多个线程提交的任务。该任务实际上由两部分组成 - perform 具有有意义的结果,cleanup 需要相当长的时间但没有返回有意义的结果。目前(显然不正确)实现看起来像这样。有没有一种优雅的方法来确保另一个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);
}
}
【问题讨论】:
-
按正确的方式提交不应该是这样吗?例如,执行、清理、执行、清理。
-
为什么不只是
pool.submit(() -> { w.cleanup(); return w.perform(); }); -
@СӏаџԁеМаятіи 这可能会不必要地延迟
perform()。想象一下cleanup()需要一分钟,perform()需要一秒钟,我们每两分钟提交一个任务。 -
但是你的池只有一个线程。它们不会同时运行。所以这就是重点?
标签: java multithreading