gpt4 book ai didi

Java 线程中断标志被清除

转载 作者:行者123 更新时间:2023-12-02 10:13:06 29 4
gpt4 key购买 nike

我正在尝试java中的中断,并观察到,如果我中断一个线程并且当线程状态从RUNNABLE更改为TERMINATED时不重置它的中断状态,则中断变量将被重置(interrupted变为false)

Main.java

public class Main {

public static void main(String[] args) {

try {

t1 t1 = new t1();
t1.start();

Thread.sleep(10);
t1.interrupt();
System.out.println("t1.isInterrupted: " + t1.isInterrupted() + " t1.state: " + t1.getState());
Thread.sleep(20);
System.out.println("t1.isInterrupted: " + t1.isInterrupted() + " t1.state: " + t1.getState());

} catch (Exception exc) {
System.out.println("Exception: " + exc);
}

}

}

t1.java

public class t1 extends Thread {

@Override
public void run() {

while (!Thread.currentThread().isInterrupted()) {
System.out.println("Processing");
}

System.out.println("Execution completed - interrupt status: " + Thread.currentThread().isInterrupted());
}

}

Main.java 的输出(Centos 7 64 位,Java 1.8.0_66-b17)

  • 处理
    加工
    加工
    t1.isInterrupted: true t1.state: RUNNABLE
    执行完成 - 中断状态:true
    t1.isInterrupted: false t1.state: 已终止

我的问题是谁或什么将此标志设置回 false,为什么? Thread 类有一个私有(private)退出方法,它将一些内部变量设置为 null,但我找不到任何重置中断标志的东西。如果有人能阐明这个问题,我将不胜感激......

PS:这里是GIST的链接

最佳答案

My question is who or what sets this flag back to false and why ?

这是线程终止时的已知行为。因为它不再运行,所以中断状态为假。中断状态在线程终止之前为 true,但在线程完成后设置为 false。

引用Thread.isInterrupted() javadocs :

A thread interruption ignored because a thread was not alive at the time of the interrupt will be reflected by this method returning false.

关于Java 线程中断标志被清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42251517/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com