简体   繁体   English

Java 线程中断标志被清除

[英]Java Thread Interrupted Flag Gets Cleared

I was experimenting with interrupts in java and observed that if i interrupt a thread and do not reset it's interrupt status when the thread state changed from RUNNABLE to TERMINATED interrupted variable gets reset (interrupted becomes false)我在 java 中尝试中断并观察到,如果我中断一个线程并且在线程状态从 RUNNABLE 更改为 TERMINATED 中断变量时不重置它的中断状态被重置(中断变为假)

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 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());
}

} }

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

  • Processing加工
    Processing加工
    Processing加工
    t1.isInterrupted: true t1.state: RUNNABLE t1.isInterrupted: true t1.state: RUNNABLE
    Execution completed - interrupt status: true执行完成 -中断状态:true
    t1.isInterrupted: false t1.state: TERMINATED t1.isInterrupted: false t1.state: TERMINATED

My question is who or what sets this flag back to false and why ?我的问题是是谁或什么将该标志设置为 false,为什么? Thread class has a private exit method that sets some internal variables to null but i couldnt find anything that resets interrupted flag. Thread 类有一个私有退出方法,该方法将一些内部变量设置为 null,但我找不到任何可以重置中断标志的东西。 If anyone can shed some light on the issue i will be grateful ...如果有人可以对这个问题有所了解,我将不胜感激......

PS: here is a link to GIST PS:这里是GIST的链接

My question is who or what sets this flag back to false and why ?我的问题是是谁或什么将该标志设置为 false,为什么?

This is the known behavior when the thread terminates.这是线程终止时的已知行为。 Because it is no longer running, the interrupt state is false.因为不再运行,中断状态为假。 The interrupt state is true right before the thread terminates but is set to false once it has completed.中断状态在线程终止前为真,但在线程完成后设置为假。

To quote the Thread.isInterrupted() javadocs :引用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.由于线程在中断时未处于活动状态而被忽略的线程中断将通过此方法返回 false 来反映。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM