使用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... |