天天看点

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..." );

}