線程interrupt方法中斷的實質

來源:互聯網
上載者:User

首先有兩段代碼:

代碼1:

//線程的中斷操作(1)<br />class MyThread implements Runnable<br />{<br />public void run(){<br />System.out.println("1、進入run方法");<br />try{<br />Thread.sleep(10000); //sleep方法會拋出一個中斷異常<br />}catch(InterruptedException e){<br />System.out.println("2、線程被中斷"); //當sleep被打斷時,則執行此中斷處理<br />}<br />System.out.println("3、run方法執行完成");<br />}<br />}<br />public class ThreadInterruptDemo01<br />{<br />public static void main(String args[]){<br />MyThread my = new MyThread();<br />Thread t = new Thread(my);<br />t.start();<br />try{<br />Thread.sleep(2000); //主線程休息2秒<br />}<br />catch(Exception e){}<br />t.interrupt(); //中斷線程<br />}</p><p>}

 

代碼2:

//線程的中斷操作(2)線程沒有被中斷,interrupt只能中斷sleep,wait等方法<br />class MyThread implements Runnable<br />{<br />public void run(){<br />System.out.println("1、進入run方法");<br />for(int i = 0;i<=10000;i++){<br />System.out.println("線程在執行"+"--"+i);<br />}<br />System.out.println("線程正常執行完畢");<br />}<br />}<br />public class ThreadInterruptDemo02<br />{<br />public static void main(String args[]){<br />MyThread my = new MyThread();<br />Thread t = new Thread(my);<br />t.start();</p><p>t.interrupt(); //中斷線程<br />}<br />}

 

     通過兩段代碼的運行結果可以知道,代碼1的中斷實現了,而代碼2的中斷沒有實現,interrupt並沒有中斷線程的執行,而是中斷了sleep的執行。原因何在,這與Interrupt的中斷內容有關。interrupt只能中斷sleep,wait等方法,而通過查詢api可以看到,sleep和wait都有InterruptedException(中斷異常)需要處理。所以可以這樣看:interrupt只能中斷會拋出中斷異常的方法,這才是interrupt的實際作用。

      還有一點需要注意,當sleep方法被中斷後,sleep方法後的內容依然會被執行,相當於線程被喚醒進入了正常執行。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.