简体   繁体   中英

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. 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). 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?

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<?> . You can then call get which may return an ExecutionException if something went wrong:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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