Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/unity3d/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java线程#isInterrupt对于死线程返回始终为false_Java_Multithreading - Fatal编程技术网

java线程#isInterrupt对于死线程返回始终为false

java线程#isInterrupt对于死线程返回始终为false,java,multithreading,Java,Multithreading,我面临着奇怪的行为。所有源都告诉您,在捕获中断异常后,需要调用Thread.currentThread().interrupt(),以恢复中断标志。但我试图创建一个简单的应用程序,在进程被中断后检查中断状态 public class Main { public static void main(String[] args) throws InterruptedException { Runnable r = () -> { try {

我面临着奇怪的行为。所有源都告诉您,在捕获中断异常后,需要调用Thread.currentThread().interrupt(),以恢复中断标志。但我试图创建一个简单的应用程序,在进程被中断后检查中断状态

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Runnable r = () -> {
            try {
                Thread.sleep(100000);
            } catch (InterruptedException e) {
                System.out.println("interrupted exception is occurred");
                Thread.currentThread().interrupt();
                System.out.println("interrupt flag is updated:" + Thread.currentThread().isInterrupted());
            }
        };

        Thread thread = new Thread(r);
        thread.start();
        thread.interrupt();

        boolean interruptFlag;
        do {
            Thread.sleep(1000);
            interruptFlag = thread.isInterrupted();
            System.out.println("interrupt flag:" + interruptFlag + " isAlive:" + thread.isAlive());
        } while (!interruptFlag);
    }
}
如果你试着运行它,你就会

interrupted exception is occurred
interrupt flag is updated:true
interrupt flag:false isAlive:false
interrupt flag:false isAlive:false
interrupt flag:false isAlive:false
interrupt flag:false isAlive:false
interrupt flag:false isAlive:false

它将无限工作。问题是为什么在线程死后iterrupt标志为false?

当您从主线程检查中断状态时,第二个线程已经死了,因此它返回false。尝试将Thread.sleep(1000)放在等待循环的末尾,您将在中断状态下看到true


这种行为没有文档记录,所以很难说是缺少文档记录还是现有实现的一个特性。私有本机布尔中断(布尔ClearInterrupted)的实现;方法需要检查才能说得更多


类似的讨论:

@MuratK。错误的副本。OP使用
Thread.currentThread().interrupt()更改状态
interruptFlag
需要是
易失性的
,不能中断不再处于活动状态的线程。不,情况结束了,如果您查看catch,您将看到我还原了中断标志。不处于活动状态的线程不是iterrupted,代码sneep start thread,然后中断它,然后检查flag@EJP局部变量不能也不需要是易变的。当线程处于活动状态时,OP将中断标志设置为true。到目前为止,我还没有找到在线程退出时重置中断标志的文档。是的,我考虑过。但我没有在文件中找到它为什么它死了重要?其中指定了在线程退出时清除中断标志(或者
isInterrupted
总是在线程死后返回flast)?此行为没有文档记录,因此很难说是缺少文档还是现有实现的一个功能。我需要检查私有本机布尔isInterrupted(布尔ClearInterrupted)的实现;方法多说。这里也有类似的讨论:这是正确的副本,不幸的是OP接受了错误的副本。请将您的评论编辑到您的答案中。