java - 连续执行两个任务

标签 java multithreading

有一个带有单个线程的线程池,用于执行多个线程提交的任务。该任务实际上由两部分组成 - 具有有意义结果的执行和需要相当长的时间但不返回任何有意义结果的清理。目前(显然不正确)的实现看起来像这样。有没有一种优雅的方法来确保另一个 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/

相关文章:

java - 使用 JAXB 从 XML 创建 POJO

java - java中的byte[]链表

java - 获取 Spring Data 上按日期排序的最后记录

multithreading - 线程池、线程安全队列、OOP

java - 使用系统属性中的静态最终字段进行单元测试

mysql - 如何找到Mysql线程

c# - 使用线程池对后台线程进行异常处理

python - Python线程传递状态

c++ - 使用两个线程和system()命令运行shell脚本: how to make sure that one shell script is started before another

java - GUI 堆栈溢出错误