synchronized关键字的Java多线程用途

标签 java multithreading concurrency synchronization thread-safety

来自 Nutshell 6th edition 中的 Java 书可以阅读:

The reason we use the word synchronized as the keyword for “requires temporary exclusive access” is that in addition to acquiring the monitor, the JVM also rereads the current state of the object from the main memory when the block is entered. Similarly, when the synchronized block or method is exited, the JVM flushes any modified state of the object back to the main memory.


也:

Without synchronization, different CPU cores in the system may not see the same view of memory and memory inconsistencies can damage the state of a running the program, as we saw in our ATM example.


它建议在进入同步方法时从主内存加载对象以保持内存一致性
但是对于没有同步关键字的对象也是这样吗?那么如果一个普通的对象在一个 CPU 的一个核心中被修改,是否会与主存同步,以便其他核心可以看到呢?

最佳答案

而另一个答案谈到缓存同步和内存层次结构的重要性,synchronized关键字不控制整个对象的状态;相反,它是关于 与该对象相关联。
Java中的每个对象实例都可以有一个关联的锁,它可以防止多个线程同时运行那些在锁上同步的 block 。这要么隐含在 this 上实例或同步关键字的参数(或静态方法的类)。
虽然 JMM 语义说这个锁对象得到了适当的控制并且在缓存级别中可用,但这并不一定意味着整个对象都受到保护;例如,当单个线程在同步块(synchronized block)或方法中运行时,从不同线程读取的字段不会被处理。
此外,Java 内存模型定义了“发生之前”关系,即数据更改如何在您需要考虑的线程之间变得可见,这就是存在“volatile”关键字和 AtomicXxxx 类型的原因,包括 var 处理宽松的内存模型.
因此,当您谈论同步时,您需要注意它只拍摄对象锁定的状态,而不是它正在保护的对象内的状态。

关于synchronized关键字的Java多线程用途,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66183264/

相关文章:

java - 线程调度 - 按设定顺序运行线程

java - LibGDX 中的自定义垂直进度条

linux - shell 脚本: Parallelizing commands in bash script under Ubuntu linux

c# - 线程中的 TopMost 表单?

java - 如何杀死等待中的线程?

for-loop - 对于范围与静态 channel 长度 golang

c++ - 将一个函数声明为 transaction_safe 就足够了,所以它们可以线程安全地使用吗?

java - Drools 单例 StatefulKnowledgeSession 作为 Web 服务

java - DynamicJasper - 如何将子报表添加为列?

java - 如何创建二维集合?