簡體   English   中英

Java 1.6-從執行程序服務線程返回到Main類

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

我正在執行我的Main類中的三個任務,方法是使用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的情況下從這些線程返回某些東西嗎?

與其通過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
}

您可以實現自己的“ FutureTask”類,並將其作為A的構造函數的參數提供:

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

每當A中發生錯誤時,您都將返回值存儲在MyFutureTask中,然后可以像使用普通FutureTask一樣讀取它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM