2012-02-23 30 views
4

如果連接線程不起作用,建議做什麼?Java:如果加入線程無效:中斷還是繼續?

 for (List t : threads) { 
      try { 
       t.join(); 
      } catch (InterruptedException e) { 
       log.error("Thread " + t.getId() + " interrupted: " + e); 
       // and now? 
      } 
     } 

是將它推薦給打破,然後(什麼與不是嗎?加入其他線程接下來會發生),或者你至少應該嘗試加入線程的休息,然後去?

感謝您的建議!

==>結論:您應該再次嘗試加入特定線程t或者您應該中斷此特定線程t並繼續。

 for (List t : threads) { 
     try { 
      t.join(); 
     } catch (InterruptedException e) {  
      try { 
       // try once! again: 
       t.join(); 
      } catch (InterruptedException ex) { 
       // once again exception caught, so: 
       t.interrupt(); 
      } 
     } 
     } 

那麼您對此解決方案有何看法?並且做「t.interrupt()」或者它應該是Thread.currentThread()。interrupt(); ?

謝謝! :-)

+0

取決於你想要做什麼...... – m0skit0 2012-02-23 10:52:16

+1

我想你就錯了。正如@aix所說的,如果拋出異常,那麼它的當前線程已被中斷。在這種情況下不是線程't'。 – Johannes 2012-02-23 10:55:48

+0

所以無論如何,你會建議我做什麼?打破程序?繼續加入列表中的下一個線程?再次嘗試加入列表中的所有線程?再試一次只加入特定的線程t?感謝:-) – nano7 2012-02-23 11:52:04

回答

2

你得到一個InterruptedException,因爲其他一些線程中斷了這個連接線程,而不是因爲join沒有「工作」。引用自API documentation

InterruptedException - 如果另一個線程中斷了當前線程。拋出此異常時,當前線程的中斷狀態將被清除。


我會建議你再歸隊線程,例如:

for (List t : threads) { 
    while (true) { 
     try { 
      t.join(); 
      break; 
     } catch (InterruptedException e) { 
      Thread.currentThread().interrupt(); 
      // ... and ignore the interrupt 
     } 
    } 
} 
+0

所以在你看來,我應該再次通過我的線程列表,並加入他們?只要重試加入特定的線程t然後繼續與其他人一起就足夠了嗎?無論如何,你不會打破加盟,是真的嗎? – nano7 2012-02-23 11:50:29

+0

是的,這將是一個很好的解決方案。 – dacwe 2012-02-23 12:05:36

+1

對不起,爲了解決問題:什麼是好的解決方案?再次加入所有線程或再次加入SPECIFIC線程,然後與其他人一起繼續?謝謝:-) – nano7 2012-02-23 12:13:38