0

我在我的java程序中寫了很多異步未來任務調用。得到下述未來的任務異步調用異常發生時掛起

FutureTask<List<ConditionFact>> x = getConditionFacts(final Member member); 
FutureTask<List<RiskFact>> x = getRiskFacts(final Member member); 
FutureTask<List<SAEFact>> x = getSAEFacts(final Member member); 

一個樣品現在假設我故意在第二次調用創建一個例外上方,包圍所有3次調用get()一個try/catch塊內我沒有看到異常來catch塊和我的Java程序只是靜止不動。所有3個方法調用都是同時發生的。

try { 
FutureTask<List<ConditionFact>> task = getConditionFacts(member); 
     // wait for the task to complete and get the result: 

      List<ConditionFact> conditionFacts = task.get(); 

     FutureTask<List<ConditionFact>> task = getRiskFacts(member); 
     // wait for the task to complete and get the result: 

      List<RiskFact> conditionFacts = task.get(); 
     } 
     catch (ExecutionException e) { 
      // an exception occurred. 
      Throwable cause = e.getCause(); // cause is the original exception thrown by the DAO 
     } 

但是,如果我把每個get()放在單獨的try catch塊中,我就可以捕獲它們。爲什麼?另外,當我開始在try catch塊中放入每個get()方法時,我就失去了多線程。該方法的調用是由一個作爲編碼

 FutureTask<List<ConditionFact>> task = getConditionFacts(member); 
    // wait for the task to complete and get the result: 
    try { 
     List<ConditionFact> conditionFacts = task.get(); 
    } 
    catch (ExecutionException e) { 
     // an exception occurred. 
     Throwable cause = e.getCause(); // cause is the original exception thrown by the DAO 
    } 
    FutureTask<List<ConditionFact>> task = getRiskFacts(member); 
    // wait for the task to complete and get the result: 
    try { 
     List<RiskFact> conditionFacts = task.get(); 
    } 
    catch (ExecutionException e) { 
     // an exception occurred. 
     Throwable cause = e.getCause(); // cause is the original exception thrown by the DAO 
    } 

發生之一,當我能夠趕上我我失去的多線程例外,當我能夠產卵多線程我失去了異常。

任何想法如何單獨處理異常,並實現多線程在同一時間

回答

2

我真的關閉了。正確的答案是使用ExecutorService在線程池中運行任務。

ExecutorService executor = Executor.newFixedThreadPool(2); 
FutureTask<List<ConditionFact>> task1 = getConditionFacts(member); 
FutureTask<List<ConditionFact>> task2 = getRiskFacts(member); 
executor.execute(task1); 
executor.execute(task2); 
// wait for the task to complete and get the result: 
try { 
    List<ConditionFact> conditionFacts = task1.get(); 
} 
catch (ExecutionException e) { 
    // an exception occurred. 
    Throwable cause = e.getCause(); // cause is the original exception thrown by the DAO 
} 
// wait for the task to complete and get the result: 
try { 
    List<RiskFact> conditionFacts = task2.get(); 
} 
catch (ExecutionException e) { 
    // an exception occurred. 
    Throwable cause = e.getCause(); // cause is the original exception thrown by the DAO 
} 

這將解決單線程執行問題。我在這裏得到了答案:http://programmingexamples.wikidot.com/futuretask

+0

程序仍然掛起... – Shiv

0

的ExecutorCompletionService應該幫助解決你的問題。您的代碼需要實現隊列機制來處理結果,並且ExecutorCompletionService應該有所幫助。一探究竟。

+0

讓我看看那 – Shiv