Java怎樣中斷一個運行中的線程(2)

來源:互聯網
上載者:User

使用Thread.interrupt()中斷線程

正如Listing A中所描述的,Thread.interrupt()方法不會中斷一個正在啟動並執行線程。這一方法實際上完成的是,線上程受到阻塞時拋出一個中斷訊號,這樣線程就得以退出阻塞的狀態。更確切的說,如果線程被Object.wait, Thread.join和 Thread.sleep三種方法之一阻塞,那麼,它將接收到一個中斷異常(InterruptedException),從而提早地終結被阻塞狀態。

因此,如果線程被上述幾種方法阻塞,正確的停止線程方式是設定共用變數,並調用interrupt()(注意變數應該先設定)。如果線程沒有被阻塞,這時調用interrupt()將不起作用;否則,線程就將得到異常(該線程必須事先預備好處理此狀況),接著逃離阻塞狀態。在任何一種情況中,最後線程都將檢查共用變數然後再停止。Listing C這個樣本描述了該技術。

Listing Cclass Example3 extends Thread {  volatile boolean stop = false;  public static void main( String args[] ) throws Exception {   Example3 thread = new Example3();   System.out.println( "Starting thread..." );   thread.start();   Thread.sleep( 3000 );   System.out.println( "Asking thread to stop..." );   thread.stop = true;//如果線程阻塞,將不會檢查此變數   thread.interrupt();   Thread.sleep( 3000 );   System.out.println( "Stopping application..." );   //System.exit( 0 );  }  public void run() {    while ( !stop ) {     System.out.println( "Thread running..." );      try {      Thread.sleep( 1000 );      } catch ( InterruptedException e ) {      System.out.println( "Thread interrupted..." );      }    }   System.out.println( "Thread exiting under request..." );  }}

一旦Listing C中的Thread.interrupt()被調用,線程便收到一個異常,於是逃離了阻塞狀態並確定應該停止。運行以上代碼將得到下面的輸出:

Starting thread...Thread running...Thread running...Thread running...Asking thread to stop...Thread interrupted...Thread exiting under request...Stopping application...

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.