gpt4 book ai didi

java - CyclicBarrier 的可见性同步?

转载 作者:太空宇宙 更新时间:2023-11-04 07:29:56 27 4
gpt4 key购买 nike

当在 Java 中使用 CyclicBarrier 同步线程时,它们是否同步非 volatile 变量?

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...

最佳答案

是的,可见性正如您所期望的那样发生,正如您从 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.

关于java - CyclicBarrier 的可见性同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17897732/

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