Java 1.6 - 从执行程序服务线程返回主类

标签 java multithreading executorservice threadpoolexecutor

我通过使用执行器服务创建 3 个线程(扩展 Runnable)并提交它们来执行主类中的三个任务。如下所示:

    ExecutorService executor = Executors
                        .newFixedThreadPool(3);

                A a= new A();
                B b= new B();
                C c= new C();

                /**
                 * Submit/Execute the jobs
                 */
                executor.execute(a);
                executor.execute(b);
                executor.execute(c);
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    //handle - show info
                    executor.shutdownNow();
                }

当线程中发生异常时,我捕获它并执行 System.exit(-1)。但是,如果发生任何异常,我需要返回到主类并在那里执行一些语句。这个怎么做?我们可以在没有 FutureTask 的情况下从这些线程返回一些东西吗?

最佳答案

而不是通过 execute 提交任务这不会给你任何捕获 run 之外的异常的能力。方法,使用 submit返回 Future<?> .然后您可以调用 get这可能会返回 ExecutionException如果出现问题:

Future<?> fa = executor.submit(a);
try {
    fa.get();  // wait on the future
} catch(ExecutionException e) {
    System.out.println("Something went wrong: " + e.getCause());
    // do something specific
}

关于Java 1.6 - 从执行程序服务线程返回主类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29677186/

相关文章:

c# - Progressbar 不报告进度

c++ - 如何在 native C++ 中跨线程调用(在主线程上回调)

java - 停止 Tomcat 时,ExecutorService 不会从 contextDestroyed() 关闭

java - 在调用 CompletableFuture.completeExceptionally(Throwable) 之前捕获 throwable 与异常

java - 不幸的是,MyApp已停止。我该如何解决?

java - 对具有不同对象的数组列表进行排序

c++ - 线程安全的缓冲区数组

java - 我如何知道 ExecutorService 何时完成 ES 上的项目是否可以重新提交到 ES

java - 如何使用 javac 跨不同平台创建二进制相同的类文件?

java - 清理 KML 流以更改 xml 命名空间