java - 在线程上调用 interrupt() 是否会创建与被中断线程的 happens-before 关系

标签 java multithreading concurrency

换句话说,我想知道在中断线程中检测到中断时,在中断之前更改变量是否始终可见。例如

private int sharedVariable;

public static void interruptTest() {
    Thread someThread = new Thread(() -> {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // Is it here guaranteed that changes before interrupt are always visible here?
            System.out.println(sharedVariable);
        }
    });
    someThread.start();
    Thread.sleep(1000);
    sharedVariable = 10;
    someThread.interrupt();
}

我试图在 Java language specification 中找到答案并在 Summary page of the java.util.concurrent packageJava tutorial 中提到但是没有提到 interrupt

我知道 volatile 和其他同步原语,但我需要它们吗?

最佳答案

是的,从线程 T1 中断线程 T2 会在 T1 和 T2 之间创建一个先发生关系,如 JLS 中所述<强>17.4.4。同步顺序:

If thread T1 interrupts thread T2, the interrupt by T1 synchronizes-with any point where any other thread (including T2) determines that T2 has been interrupted (by having an InterruptedException thrown or by invoking Thread.interrupted or Thread.isInterrupted).

现在这仅意味着 T1 同步中断 T2 的检测,而您询问的是先于。幸运的是,前者暗示了 17.4.5 中的后者。先于顺序发生:

Two actions can be ordered by a happens-before relationship. If one action happens-before another, then the first is visible to and ordered before the second.

If we have two actions x and y, we write hb(x, y) to indicate that x happens-before y.

  • ...
  • If an action x synchronizes-with a following action y, then we also have hb(x, y).

因此即使没有 volatile,您也可以安全地访问 sharedVariable,因为它(至少)具有 T1 写入的值。

关于java - 在线程上调用 interrupt() 是否会创建与被中断线程的 happens-before 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45269123/

相关文章:

java - 使用线程和 Swing 显示更新延迟

java - 使用javamail api从地址获取?

java - 如何使用android以编程方式找到网络上IP Cam的IP地址

java - 如何实现独写,非独读?

java - 获取控制当前类的java线程

multithreading - 每个唯一 id 不超过一个并发线程运行代码的算法

Java 并发 : Are "get(Key) for HashMap and ConcurrentHashMap equal in performance?

java - 为什么 Java 看不到来自另一个线程的更新值?

java - 如何在tomcat中执行war包中的一些初始化代码?

java - java中如何使两个对象相等