在与中断线程的关系之前,是否在线程上调用interrupt() [英] Does calling interrupt() on a thread create happens-before relation with the interrupted thread

查看:146
本文介绍了在与中断线程的关系之前,是否在线程上调用interrupt()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In other words I want to know if changing variable before interrupt is always visible when interrupt is detected inside interrupted thread. E.g.

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语言规范
java.util.concurrent包的摘要页面 Java教程中提到但是中断没有被提及。

I tried to find answer in Java language specification and in Summary page of the java.util.concurrent package mentioned in Java tutorial but interrupt was not mentioned.

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

I know about volatile and other synchronize primitives but do I need them?

推荐答案

是的,从线程T1中断线程T2会产生发生之前 T1和T2之间的关系,如 JLS 17.4.4。同步订单

Yes, interrupting a thread T2 from a thread T1 creates a happens-before relationship between T1 and T2, as described in the JLS 17.4.4. Synchronization Order:


如果线程T1中断线程T2,则T1
的中断与任何点同步任何其他线程(包括T2)
确定T2已被中断(通过抛出
InterruptedException或通过调用Thread.interrupted或
Thread.isInterrupted)。

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。发生在订单之前

Now that only implies that T1 synchronizes-with the detection of the interrupt T2, while you asked about happens-before. Luckily the former implies the latter from 17.4.5. Happens-before Order:


可以通过before-before关系订购两个操作。如果一个
的操作发生在另一个之前,那么第一个是可见的,而
在第二个之前订购。

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.

如果我们有两个动作x和y,我们写hb(x,y)表示x
发生在y之前。

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


  • ...

  • 如果动作x与后续动作y同步,那么我们也有hb(x,y)。

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

So you are safe to access sharedVariable knowing that it has (at least) the value written by T1, even without volatile.

这篇关于在与中断线程的关系之前,是否在线程上调用interrupt()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆