2012-12-05 68 views
-1

我開始我的主題是這樣的:Java線程中斷()。這是正常的例外嗎?

public void startTask(Runnable r) 
{ 
    running = true; 
    Log.i(tag, "-----------start.Runnable-----------"); 

    final Thread first = new Thread(r); 
    currentTask = first; 
    first.start(); 

    Thread second = new Thread(new Runnable() { 

     @Override 
     public void run() { 
      try{ 
       first.join(); 
      } 
      catch(InterruptedException e){ 

      } 
      running = false; 
     } 
    }); 

    second.start(); 

} 

而當我想取消當前的操作,我做這樣一個Theread根據這篇文章:http://forward.com.au/javaProgramming/HowToStopAThread.html

public void cancelTask() 
{ 
    Log.i(tag, "-----------cancelTask()-----------"); 
    try{ 
     currentTask.interrupt(); 
     running = false; 
    } 
    catch(SecurityException e){ 
     e.printStackTrace(); 
    } 
} 

應用仍然是在cancelTask​​後運行,但我有例外:

12-05 20:29:00.274: W/System.err(13533): java.lang.InterruptedException 
12-05 20:29:00.274: W/System.err(13533): at java.lang.VMThread.sleep(Native Method) 
12-05 20:29:00.294: W/System.err(13533): at java.lang.Thread.sleep(Thread.java:1047) 
12-05 20:29:00.294: W/System.err(13533): at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:331) 
12-05 20:29:00.304: W/System.err(13533): at com.rsd.myfirstapp3.ProgressServiceActivity$2.run(ProgressServiceActivity.java:174) 
12-05 20:29:00.314: W/System.err(13533): at java.lang.Thread.run(Thread.java:864) 

這樣的線程操作是否正常?

+3

呃,是的......這就是中斷一個線程*做*。 –

+1

[www.ibm.com/developerworks/java/library/j-jtp05236/index.html](http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html) – didierc

回答

0

線程自行停止或外部進程停止。意味着一個線程在完成它所做的任何事後完成它的執行,此時InterruptedException不會被拋出(這是顯而易見的)。但是父線程(啓動線程的線程)可能希望在其執行期間停止正在執行的線程,在這種情況下會拋出異常InterruptedException,並且此線程接收到此異常。這主要是因爲這個步驟當它被外部進程/父線程停止時想要做某些事情(清理資源,關閉IO等)。 Refer