我通过使用执行器服务创建 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/