java - 启动多个线程并在所有子线程完成后在父线程上运行 callabck 的非阻塞方法

标签 java multithreading concurrency java.util.concurrent

主要是回调应该在父线程上,而不是从完成工作的任务中调用(例如,不像 ThreadPoolExecutor 的 afterExecute() Hook )。 我想要这样的东西:

ExecutorService exec = Executors.newSingleThreadExecutor();
>>>>> exec.addAllJobsFinishedListener(someListener) <<<<<
exec.submit(task);

和 someListener 有一个像 allJobsFinished() 这样的 Overrideable 方法

最佳答案

Non-blocking method to start several threads and run a callback on the parent thread when all children have finished

如果你想在父线程上回调,恐怕你需要让父线程调用exec.awaitTermination(...)。在您提交所有作业并调用 exec.shutdown() 之后,这将等待线程池中的所有作业完成。如果您希望这是非阻塞的,那么您将不得不在另一个线程中执行此操作(当然是在不同的池中运行)。

我不明白它如何成为在也是非阻塞的父线程上运行的“监听器”。您可以进行后台线程检查,当 exec.awaitTermination(...) 完成。

ThreadPoolExecutor 确实有您可以覆盖的 terminate() 方法。那不是你想要的吗?这是 javadocs对于方法。您的代码看起来像这样:

ThreadPoolExecutor threadPool =
   new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS,
      new LinkedBlockingQueue()) {
     public void terminated() {
        super.terminated();
        // do something magic
     }
};
threadPool.execute(task);
// ...
// need to shutdown the pool after you've submitted all of the tasks
threadPool.shutdown();

如果“神奇的东西”代码设置了一个共享的 volatile boolean 或一个主线程可以检查的 AtomicBoolean,那么它应该可以正常工作。

关于java - 启动多个线程并在所有子线程完成后在父线程上运行 callabck 的非阻塞方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19145760/

相关文章:

java - 线程并发——使用字符串对象的锁进行同步

java - Spring 3.1.1 MVC @Cacheable 没有被击中

java - Collections.sort() 没有按应有的方式排序

c++ - QThread : Destroyed while thread is still running in QTest

java - 在多线程程序中更新共享资源

mysql - 不间断查询

java - 将字符串从 Web 服务转换为 JSON 数组

java - Android 游戏时间处理

c# - NLog 的线程安全性如何?

java - 转换实现 Runnable 的对象