gpt4 book ai didi

java - Java 中的 protected block 。我应该在哪里更新条件变量?

转载 作者:行者123 更新时间:2023-12-01 11:36:42 27 4
gpt4 key购买 nike

我会使用 volatile 条件变量,但我认为 volatile 是多余的。此外,我不太确定我从https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html#MemoryVisibility中理解了这一点。正确的是:

An unlock (synchronized block or method exit) of a monitor happens-before every subsequent lock (synchronized block or method entry) of that same monitor. And because the happens-before relation is transitive, all actions of a thread prior to unlocking happen-before all actions subsequent to any thread locking that monitor.

因此随后调用同步 block 。但是,在 synchronized block 中执行的赋值结果对所有后续 synchronized block 可见吗?

这是一个示例应用程序。

package sample;

public class Foo {

private boolean shouldWait;
private final Object lock = new Object();

void blockThread() {
synchronized (lock) {
shouldWait = true;
while (shouldWait) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

void notifyThread() {
synchronized (lock) {
shouldWait = false;
lock.notify();
}
}
}

测试。

package sample;

public class Main {

private static Foo foo = new Foo();

public static void main(String[] args) {
new Thread(new Runnable() {

@Override
public void run() {
foo.blockThread();
}
}).start();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
new Thread(new Runnable() {

@Override
public void run() {
foo.notifyThread();
}
}).start();
}

}

最佳答案

So synchronized blocks are called subsequently. But are results of assignments performed in a synchronized block visible to all the subsequent synchronized blocks?

是的。 volatile 写入具有相同的关系。 volatile 写入之前的所有操作都发生在所有后续读取之前。

关于java - Java 中的 protected block 。我应该在哪里更新条件变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29902048/

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