通过使用Executor创建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的情况下从这些线程返回一些东西吗?
发布于 2015-04-16 14:20:09
与其通过execute提交任务(这不会使您在run方法之外捕获异常),不如使用返回Future<?>的submit。然后,您可以调用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
}发布于 2015-04-16 14:17:35
您可以实现自己的"FutureTask“类,并将其作为参数提供给A的构造函数:
MyFutureTask futureA = new MyFutureTask();
A a = new A(futureA);当A中发生错误时,您可以将返回值存储在MyFutureTask中,然后可以像读取普通FutureTask一样读取返回值。
https://stackoverflow.com/questions/29677186
复制相似问题