有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

CyclicBarrier上的java可见性同步?

在Java中使用CyclicBarrier同步线程时,它们是否同步非易失性变量

int a = 0;
int b = 0;
CyclicBarrier barrier = new CyclicBarrier(2);

/*** Thread 1 ***/
public void run() {
    a = 2;
    barrier.await();

    doSomeStuff(b); // no side-effects
}

/*** Thread 2 ***/
public void run() {
    b = 3;
    barrier.await();

    doSomeStuff(a); // no side-effects
}

我们可以确定线程1的doSomeStuff调用b已设置为3吗? 尝试时总是3


共 (1) 个答案

  1. # 1 楼答案

    是的,正如您从CyclicBarrier类的javadoc中所看到的,可视性正如您所期望的那样:

    Memory consistency effects: Actions in a thread prior to calling await() happen-before actions that are part of the barrier action, which in turn happen-before actions following a successful return from the corresponding await() in other threads.