简体   繁体   English

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

[英]Java 1.6 - Return to the Main class from an executor service thread

I'm executing three tasks from my Main class by creating 3 threads (extends Runnable) using the Executor Service and submitting them. 我正在执行我的Main类中的三个任务,方法是使用Executor服务创建3个线程(扩展Runnable)并提交它们。 Like below: 如下所示:

    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();
                }

When an exception occurs in the thread, I catch it and do System.exit(-1). 当线程中发生异常时,我将其捕获并执行System.exit(-1)。 But, I need to return to the main class if any exception occurs and execute some statements there. 但是,如果发生任何异常,我需要返回主类并在那里执行一些语句。 How to do this? 这个怎么做? Can we return something from these threads without FutureTask? 我们可以在没有FutureTask的情况下从这些线程返回某些东西吗?

Instead of submitting the task via execute which does not give you any capability of catching exception outside the run methods, use submit which returns a Future<?> . 与其通过execute提交任务,该方法不会给您任何在run方法之外捕获异常的能力,而应使用submit ,它会返回Future<?> You can then call get which may return an ExecutionException if something went wrong: 然后,您可以调用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
}

You can implement your own "FutureTask" class and give it as an argument to A's constructor: 您可以实现自己的“ FutureTask”类,并将其作为A的构造函数的参数提供:

MyFutureTask futureA = new MyFutureTask();
A a = new A(futureA);

Whenever an error happens in A you store the return value in your MyFutureTask and can then read it as your would with a normal FutureTask. 每当A中发生错误时,您都将返回值存储在MyFutureTask中,然后可以像使用普通FutureTask一样读取它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM