多线程之退出方式

笔记整理自
http://blog.csdn.net/jiaby008/article/details/6198739

注:CSDN代码块中不能加粗字体,所以语句前后被标**的即为加粗字体

首先,忘掉Thread.stop方法,虽然它确实停止了一个正在运行的线程,然而这种方法是不安全也是不受提倡的
Thread.interrupt并不会中断一个正在运行的线程。
一个线程调用interrupt()后只是改变了中断状态,它才可以继续执行下去,在没有调用sleep,wait,join等方法或自己抛出异常之前,它就可以调用interrupted()来清除中断状态(变回原状))

中断线程:最受推荐的方式是,使用共享变量(shared variable)发出信号,告诉线程必须停止正在运行的任务。
示例代码:

class Example2 extends Thread {
  **volatile boolean stop = false;**
  public static void main( String args[] ) throws Exception {
    Example2 thread = new Example2();
   System.out.println( "Starting thread..." );
   **thread.start();**
   Thread.sleep( 3000 );
   System.out.println( "Asking thread to stop..." );
   **thread.stop = true;**
   Thread.sleep( 3000 );
   System.out.println( "Stopping application..." );

  }
  public void run() {
    **while ( !stop )** {
     System.out.println( "Thread is running..." );
      long time = System.currentTimeMillis();
      while ( (System.currentTimeMillis()-time < 1000) && (!stop) ) {
      }
    }
   System.out.println( "Thread exiting under request..." );
  }
}

但是按上述实例,那么当线程被阻塞时,它便不能核查共享变量,也就不能停止(例如调用Object.wait()、ServerSocket.accept()和DatagramSocket.receive()时可能永久的阻塞线程)

使用Thread.interrupt()与共享变量中断阻塞线程

Thread.interrupt()方法不会中断一个正在运行的线程。这一方法实际上完成的是,在线程受到阻塞时抛出一个中断信号,这样线程就得以退出阻塞的状态。更确切的说,如果线程被Object.wait, Thread.join和Thread.sleep三种方法之一阻塞,那么,它将接收到一个中断异常(InterruptedException),从而提早地终结被阻塞状态
如果线程没有被阻塞,这时调用interrupt()将不起作用;否则,线程就将得到异常(该线程必须事先预备好处理此状况),接着逃离阻塞状态。
实例:

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

  }
  public void run() {
    **while ( !stop )** {
     System.out.println( "Thread running..." );
      try {
**//这里线程被阻塞,thread.interrupt()发现被Thread.sleep阻塞,则抛出阻塞异常,而后退出阻塞状态**
      **Thread.sleep( 1000 );**
      } **catch ( InterruptedException e )** {
      System.out.println( "Thread interrupted..." );
      }
    }
   System.out.println( "Thread exiting under request..." );
  }
}

中断I/O操作:

I/O操作可以阻塞线程一段相当长的时间,特别是牵扯到网络应用时。例如,服务器可能需要等待一个请求(request),又或者,一个网络应用程序可能要等待远端主机的响应。
如果你正使用通道(channels)(NIO),那么被阻塞的线程将收到一个ClosedByInterruptException异常。如果情况是这样,其代码的逻辑和上述实例中的是一样的,只是异常不同而已
但如果是传统IO,Thread.interrupt()将不起作用,因此线程将不会退出被阻塞状态。
Java为这种情形提供了一项解决方案,即调用阻塞该线程的套接字(Socket)的close()方法。在这种情形下,如果线程被I/O操作阻塞,该线程将接收到一个SocketException异常,这与使用interrupt()方法引起一个InterruptedException异常被抛出非常相似
唯一要说明的是,必须存在socket的引用(reference),只有这样close()方法才能被调用。这意味着socket对象必须被共享。
实例:

class Example5 extends Thread {
  **volatile boolean stop = false;**
  **volatile ServerSocket socket;**
  public static void main( String args[] ) throws Exception {
    Example5 thread = new Example5();
   System.out.println( "Starting thread..." );
   thread.start();
   Thread.sleep( 3000 );
   System.out.println( "Asking thread to stop..." );
   **thread.stop = true;**
   **thread.socket.close();**
   Thread.sleep( 3000 );
   System.out.println( "Stopping application..." );
   //System.exit( 0 );
  }
  public void run() {
    try {
      socket = new ServerSocket(7856);
    } catch ( IOException e ) {
     System.out.println( "Could not create the socket..." );
      return;
    }
    **while ( !stop )** {
     System.out.println( "Waiting for connection..." );
      try {
       Socket sock = socket.accept();
**//SocketException extends IOException**
      } catch ( IOException e ) {
      System.out.println( "accept() failed or interrupted..." );
      }
    }
   System.out.println( "Thread exiting under request..." );
  }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值