Executor框架中所有线程都执行完毕时捕获一个事件

Capture a event when all the threads are executed in Executor framework

我正在使用 Java 执行器框架同时执行多个线程。我想在所有线程执行完后做一些操作。我们在执行器框架中是否有任何侦听器或事件捕获机制

ThreadPoolExecutor 的 API 停靠描述了一些可能对此有用的挂钩:

Hook methods

This class provides protected overridable beforeExecute(java.lang.Thread, java.lang.Runnable) and afterExecute(java.lang.Runnable, java.lang.Throwable) methods that are called before and after execution of each task. These can be used to manipulate the execution environment; for example, reinitializing ThreadLocals, gathering statistics, or adding log entries. Additionally, method terminated() can be overridden to perform any special processing that needs to be done once the Executor has fully terminated.

If hook or callback methods throw exceptions, internal worker threads may in turn fail and abruptly terminate.

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html

        A a = new A();
        B b= new B();
        FutureTask fa = new FutureTask (a);
        FutureTask fb = new FutureTask (b);
        ExecutorService es = Executors.newFixedThreadPool(2); 
        es.submit (fa);
        es.submit(fb);



        String getName = (String)a.get();
        String getSurName = (String)b.get();

        es.shutdown ();

        ***//Here all threads are executed and 
        //you can write any code which you want to execute after 
         //finishing all the threads.***

或其他解决方法。 .... 您可以使用 LocalThrad class 编写守护程序 class 并生成线程,它将充当您的监听器。

无论你想在这种情况下实现什么,你都可以通过使用上面的守护进程来实现 class。

您可以考虑从 ThreadPoolExecutor to a ScheduledThreadPoolExecutor. The difference is, that for all the tasks you enqueue, you'll get a Future<T>

这使您可以检查 .isDone() 您提交的任务并采取相应的行动。如果您需要使用您提交的结果,则特别有趣,因为您可以干净地执行 .get() 然后,在执行完成之前不会阻塞调用线程。

另一种选择可能是实现 ThreadFactory,它会为 join() 主线程生成一个额外的侦听器线程,并在完成时通知您。