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

Har*_*ger 1 java multithreading executorservice threadpoolexecutor

我正在使用Executor Service创建3个线程(扩展Runnable)并提交它们,从我的Main类执行三个任务.如下所示:

    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();
                }
Run Code Online (Sandbox Code Playgroud)

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

Jea*_*art 5

而不是提交通过execute它的任务不会给你任何捕获run方法之外的异常的能力,而是使用submit返回a 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
}
Run Code Online (Sandbox Code Playgroud)