关于线程中断的疑问。

nobullet nobullet 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
测试代码如下:

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。请教大家,为什么会有这样的结果?
...全文

相关推荐

评论 6
收藏 已收藏
分享
返回顶部
nobullet
Java SE 62,621 成员 307,251 内容