简体   繁体   English

java中线程的中断状态标志在哪里,为什么interrupted()方法是静态的

[英]where is interrupt status flag of a thread in java , and why is interrupted() method static

First question is : where is the interrupted status flag that interrupt() method supposedly sets : 第一个问题是:interrupt()方法应该设置中断状态标志在哪里:

 public void interrupt() {
            if (this != Thread.currentThread())
                checkAccess();

            synchronized (blockerLock) {
                Interruptible b = blocker;
                if (b != null) {
                    interrupt0();           // Just to set the interrupt flag
                    b.interrupt(this);
                    return;
                }
            }
            interrupt0();
        }

Second question is : why is interrupted() method is static ? 第二个问题是:为什么interrupted()方法是静态的 and isInterrupted not static ? isInterrupted不是静态的吗?

The language specification doesn't dictate how the interruption status should be implemented. 语言规范没有规定如何实现中断状态。 In hotspot, you can find the implementation details in the JVM code. 在热点中,您可以在JVM代码中找到实现细节。 For example, for linux, it's here around line 4140. 例如,对于linux,它 4140行附近。

interrupted is static because it checks the current thread status. interrupted是静态的,因为它检查当前线程状态。 In other words, if you call new Thread().interrupted() on the main thread, you will get true if the main thread is interrupted, not if the new Thread is interrupted. 换句话说,如果您在主线程上调用new Thread().interrupted() ,则在主线程被中断的情况下将获得true,而在新线程被中断的情况下将获得true。

isInterrupted checks whether the thread on which you call the method is interrupted. isInterrupted检查您在其上调用该方法的线程是否被中断。 In the example above, it would return the status of new Thread() , ie false. 在上面的示例中,它将返回new Thread()的状态,即false。

Finally, an important difference between the two methods is that interrupted clears the interruption status. 最后,两种方法之间的重要区别是interrupted清除中断状态。 It is generally good practice to reset it, unless your code is responsible for the lifecycle of the given thread: 最好重置它,除非您的代码负责给定线程的生命周期:

if (Thread.interrupted()) {
  Thread.currentThread().interrupt();
  //etc.
}

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

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