2015-04-16 40 views
1

我使用Executor服務創建3個線程(擴展Runnable)並提交它們,從而從我的Main類執行三個任務。如下所示:Java 1.6 - 從執行器服務線程返回主類

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的情況下從這些線程返回一些內容嗎

回答

5

不提交通過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 
} 
+0

你想補充一點'Runnable's可纏繞逮住checked異常到RuntimeException'的'一個子類的實例,以重新拋出... – Holger

0

您可以實現自己的「FutureTask」類,並把它作爲參數傳遞給A的構造函數:

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

每當出錯。如果是發生了,你的返回值存儲在您的MyFutureTask,然後可以把它讀作你會用普通的FutureTask。