测试代码如下: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。请教大家,为什么会有这样的结果?

解决方案 »

  1.   

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

  2.   

    谢谢回复,连接的文章有点不好理解,请问我这样理解是否有错误:中断方法并不是真正的由jvm来中断线程的执行,而是通过设置中断标志,由程序来决定是否中断该线程?换句话说,无论被中断的线程是处于wait、sleep、join等方法中还是处于while(true)中,当该线程被调用了中断方法,中断标志都会先设置为true,而在几个时间片之后会自动设置回false?
      

  3.   

    哦 不是经过几个时间片,是jvm会保证被中断的线程一定能检测到中断标志位为true至少一次,之后才会设置回false,这么说对不?
      

  4.   


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