Java 1.6-从executor服务线程返回到主类
通过使用Executor服务创建3个线程(extends Runnable)并提交它们,我正在从我的主类执行三个任务。如下图所示:Java 1.6-从executor服务线程返回到主类,java,multithreading,executorservice,threadpoolexecutor,Java,Multithreading,Executorservice,Threadpoolexecutor,通过使用Executor服务创建3个线程(extends Runnable)并提交它们,我正在从我的主类执行三个任务。如下图所示: ExecutorService executor = Executors .newFixedThreadPool(3); A a= new A(); B b= new B(); C c= new C();
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的情况下从这些线程返回一些东西吗?您可以实现自己的“FutureTask”类,并将其作为参数提供给A的构造函数:
MyFutureTask futureA = new MyFutureTask();
A a = new A(futureA);
每当在中发生错误时,您将返回值存储在MyFutureTask中,然后可以像使用普通FutureTask一样读取它。您可以实现自己的“FutureTask”类,并将其作为参数提供给A的构造函数:
MyFutureTask futureA = new MyFutureTask();
A a = new A(futureA);
无论何时在中发生错误,您都会将返回值存储在MyFutureTask中,然后可以像正常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
}
Future fa=执行人提交(a);
试一试{
fa.get();//等待未来
}捕获(执行例外){
System.out.println(“出错:+e.getCause());
//做一些具体的事情
}
使用submit
返回未来的方法,而不是通过execute
提交任务,该方法不允许您捕获run
方法之外的异常。然后,您可以调用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
}
Future fa=执行人提交(a);
试一试{
fa.get();//等待未来
}捕获(执行例外){
System.out.println(“出错:+e.getCause());
//做一些具体的事情
}
您可以添加Runnable
s可以将捕获的已检查异常包装到RuntimeException
的子类的实例中,以便重试…您可以添加Runnable
s可以将捕获的已检查异常包装到RuntimeException
的子类的实例中,以便重试…