简体   繁体   English

在CyclicBarrier上进行可见性同步?

[英]Visibility synchronization at CyclicBarrier?

When using a CyclicBarrier for synchronizing threads in Java, do they synchronize non-volatile variables? 在使用CyclicBarrier同步Java中的线程时,它们是否同步非易失性变量?

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
}

Can we be sure that on Thread 1's doSomeStuff call b has been set to 3? 我们可以确定在线程1的doSomeStuff调用b上已设置为3吗? When trying it's always 3... 尝试时总是3 ...

Yes, visibility happens as you would expect, as you can see from the javadoc for the CyclicBarrier class: 是的,可见性如您所愿,正如您从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. 内存一致性影响:线程中的操作在调用await()之前发生在作为屏障动作一部分的动作之前,而这些动作又发生在在其他线程中从相应await()成功返回之后的动作之前。

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

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