java线程中断[interrupt()函数]
一个正常的线程中断:
从运行到真正的结束,应该有三个阶段:
正常运行.
处理结束前的工作,也就是准备结束.
结束退出.
Java曾经提供过抢占式限制中断,但问题多多,例如的Thread.stop。另一方面,出于Java应用代码的健壮性的考虑,降低了编程门槛,减少不清楚底层机制的程序员无意破坏系统的概率,这个问题很多,比如:
当在一个线程对象上调用stop()方法时,这个线程对象所运行的线程就会立即停止,并抛出特殊的ThreadDeath()异常。这里的“立即”因为太“立即”了,
一个线程正在执行:
synchronized void { x = 3; y = 4;}
volatile bool isInterrupted; //… while(!isInterrupted) { compute(); }
public class ThreadA extends Thread{ int count=0; public void run(){ System.out.println(getName()+"将要运行..."); while(!this.isInterrupted()){ System.out.println(getName()+"运行中"+count++); try{ Thread.sleep(400); }catch(InterruptedException e){ System.out.println(getName()+"从阻塞中退出..."); System.out.println("this.isInterrupted()="+this.isInterrupted()); } } System.out.println(getName()+"已经终止!"); }}
public class ThreadDemo{ public static void main(String argv[])throws InterruptedException{ ThreadA ta=new ThreadA(); ta.setName("ThreadA"); ta.start(); Thread.sleep(2000); System.out.println(ta.getName()+"正在被中断..."); ta.interrupt(); System.out.println("ta.isInterrupted()="+ta.isInterrupted()); }}
public class Thread { //设置中断标记 public void interrupt() { ... } //获取中断标记的值 public boolean isInterrupted() { ... } //清除中断标记,并返回上一次中断标记的值 public static boolean interrupted() { ... } ... }如何使用中断标记来结束你的程序就是你自己来考虑的事了,事实上JVM只为我们设计一个中断标记而已。