gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:52:40 24 4
gpt4 key购买 nike

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

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/

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