日期:2014-05-20  浏览次数:20690 次

关于线程中断的疑问。
测试代码如下:

public class testThread {

Thread t = null;
public void setT(Thread t) {
this.t = t;
}
class threadA implements Runnable{

private void paint() {
for(int i = 0; i < 20; i ++) {
System.out.println("a线程-- " + t.isInterrupted());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

@Override
public void run() {
synchronized (this) {
try {
this.wait(5000);
} catch (InterruptedException e) {
paint();
e.printStackTrace();
}
}
}
}

public static void main(String[] args) {
testThread test = new testThread();
Thread t = new Thread(test.new threadA());
test.setT(t);
t.start();

try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("中断之前- " + t.isInterrupted());
t.interrupt();
for(int i = 0; i < 20; i ++) {
System.out.println("主线程--" + t.isInterrupted());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

}

执行结果如下:
中断之前- false
主线程--true
a线程-- false
主线程--false
a线程-- false
...
之后的打印全是false,文档中说线程中断后调用isInterrupted会返回true,现在返回了false,这说明在线程遇到wait、sleep等阻塞类型方法的时候只会将其线程从执行状态改变为中断状态并发出一个InterruptedException 异常,并不会改变其标志该线程是否正在执行的布尔类型变量。但是在执行结果中可以看到在主线程中打印出一个true。请教大家,为什么会有这样的结果?

------解决方案--------------------
不是不会改变,而是又改回来了,是wait,sleep中已经处理了中断,一般处理中断简单来说有两种方式:
1、抛出InterruptedException,并将中断标志置为false;
2、不抛出InterruptedException,但中断标志仍然设置true。
http://ifeve.com/cancellation/#interruption
------解决方案--------------------
引用:
引用:不是不会改变,而是又改回来了,是wait,sleep中已经处理了中断,一般处理中断简单来说有两种方式:
1、抛出InterruptedException,并将中断标志置为false;
2、不抛出InterruptedException,但中断标志仍然设置true。
http://ifeve.com/cancellation/#int……


前面的理解是正确的,但不会自动设为false,这是自己代码干的事情,比如wait,sleep中有清除中断的代码,如果是自己写的方法,通过Thread.interrupted方法来清除