天天看點

java 結束線程 interrupt()

http://blog.csdn.net/wxwzy738/article/details/8516253

class 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();

   system.out.println( "stopping application..." );

   //system.exit( 0 );

  }

  public void run() {

    while ( !stop ) {

     system.out.println( "thread running..." );

      try {//當不使用interrupt(),stop會一直等到阻塞結束才會判斷,注意,interrupt()應該在阻塞前調用

      thread.sleep( 10000);//當調用interrupt(),運作到此處會直接補貨異常,在一場中設定stop标志,然後while判斷

      } catch ( interruptedexception e ) {

      system.out.println( "thread interrupted..." );

      }

    }

   system.out.println( "thread exiting under request..." );

}