Java怎样中断一个运行中的线程(2)

    使用Thread.interrupt()中断线程

    正如Listing A中所描述的,Thread.interrupt()方法不会中断一个正在运行的线程。这一方法实际上完成的是,在线程受到阻塞时抛出一个中断信号,这样线程就得以退出阻塞的状态。更确切的说,如果线程被Object.wait, Thread.join和 Thread.sleep三种方法之一阻塞,那么,它将接收到一个中断异常(InterruptedException),从而提早地终结被阻塞状态。

    因此,如果线程被上述几种方法阻塞,正确的停止线程方式是设置共享变量,并调用interrupt()(注意变量应该先设置)。如果线程没有被阻塞,这时调用interrupt()将不起作用;否则,线程就将得到异常(该线程必须事先预备好处理此状况),接着逃离阻塞状态。在任何一种情况中,最后线程都将检查共享变量然后再停止。Listing C这个示例描述了该技术。

    Listing C
    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();
       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...
    

你可能感兴趣的:(java,thread,c,exception,String)