gpt4 book ai didi

java - Java java.util.concurrent.locks.Lock 如何保证线程之间的内存同步?

转载 作者:行者123 更新时间:2023-11-30 08:18:56 25 4
gpt4 key购买 nike

查看这个java代码片段:

 Lock l = ReentrantLock();
l.lock();
try {
counter++;
} finally {
l.unlock();
}

这段代码保证在特定时间内只有一个线程会执行try block 中的代码。

我的问题是:锁定/解锁机制如何保证线程之间的内存可见性?(确保计数器结果由线程 X 刷新到主内存中的机制是什么? ,并且会被随后到来的线程Y从主存加载?)

最佳答案

http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4.5

17.4.5. Happens-before Order

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.

...

It follows from the above definitions that:

An unlock on a monitor happens-before every subsequent lock on that monitor.

...

In a happens-before consistent set of actions, each read sees a write that it is allowed to see by the happens-before ordering.

看到暗示是从不同的线程看到

关于java - Java java.util.concurrent.locks.Lock 如何保证线程之间的内存同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29242101/

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