2010-06-17 40 views
1

我必須在新線程上調用第三方功能模塊。從我所看到的情況來看,如果一切進展順利,或者只是掛起線索鎖定,呼叫就會很快完成。有什麼方法可以啓動線程並進行調用並等待幾秒鐘,如果線程仍然活着,然後假設它已被鎖定,則可以在不使用任何廢棄方法的情況下殺死(或停止或放棄)線程。在java中識別和處理鎖定線程的最佳方法

我現在有類似的東西,但我不確定這是否是最好的方式來做到這一點,我想避免調用Thread.stop(),因爲它已被棄用。謝謝。

private void foo() throws Exception 
{ 
     Runnable runnable = new Runnable() 
     { 

      @Override 
      public void run() 
      { 
        // stuff that could potentially lock up the thread. 
      } 
     }; 
     Thread thread; 
     thread = new Thread(runnable); 
     thread.start(); 
     thread.join(3500); 
     if (thread.isAlive()) 
     { 
      thread.stop(); 
      throw new Exception(); 
     } 

} 
+0

所以基本上你想啓動一個線程,然後停止它,如果它仍然活着一段時間後? – 2010-06-17 19:15:39

+0

@matt_b是的,正好! – 2010-06-17 19:43:02

回答

2
public void stop() { 
     if (thread != null) { 
      thread.interrupt(); 
     } 
    } 

See this link上如何停止一個線程,它涵蓋的主題以及

+1

我投票,因爲調用你的方法'停止'顯示對線程中斷充其量天真和不正確的理解。作爲FYI @Romain Hippeau,僅僅因爲你在線程中調用中斷並不意味着它會停止。如果這段代碼的執行足夠糟糕而導致死鎖,那肯定是不足以錯誤地處理InterruptedException,或者不適當地檢查中斷標誌。 – 2010-06-17 22:54:33

+0

@Tim Bender - 問題是如何阻止線程。例程的實施不是問題的一部分。如果你閱讀我在答案中的鏈接,它涵蓋了所有這些。爲了記錄,讓它顯示「我認爲投票不公平」。附:感謝您爲解釋爲什麼而不是隻是downvoting(我討厭這個) – 2010-06-18 01:38:13

0

我將調查java.util.concurrentExecutor框架,特別是Future<T>接口。有了這些,你可以從java.lang.Thread的變化中抽象出一些東西,並且你可以很好地分離它們的運行方式(無論是在單獨的線程上,線程是來自池還是實例化飛等)

未來的實例,至少,給你isDoneisCancelled方法。

ExecutorServiceExecutor的子接口)爲您提供了一些關閉任何排出任務的方法。或檢查出ExecutorService.awaitTermination(long timeout, TimeUnit unit)方法

private void foo() throws Exception 
{ 
     ExecutorService es = Executors.newFixedThreadPool(1); 

     Runnable runnable = new Runnable() 
     { 

      @Override 
      public void run() 
      { 
        // stuff that could potentially lock up the thread. 
      } 
     }; 

     Future result = es.submit(runnable); 

     es.awaitTermination(30, TimeUnit.SECONDS); 

     if (!result.isDone()){ 
      es.shutdownNow(); 
     } 

} 
1

有沒有辦法做你想要什麼(無條件)。例如,如果stuff that could potentially lock up the thread.看起來是這樣,沒有辦法阻止它,永遠短System.exit()的組成:

public void badStuff() { 
while (true) { 
    try { 
    wait(); 
    } 
    catch (InterruptedException irex) { 
    } 
} 
} 

當你的應用程序卡住,運行jstack(或使用調試器)。嘗試找出什麼堅持了功能,並修復它。

+1

或使用以下命令獲取JVM轉儲:kill -QUIT pid – 2010-06-17 19:29:58

+1

只適用於unix,jstack是跨平臺的。 – Justin 2010-06-17 19:30:56

+0

不幸的是,我調用的函數在第三方模塊中,我無法控制它。所以,除非我從模塊的作者那裏得到更新,否則無法解決它。 – 2010-06-17 19:46:56

相關問題