我一直在努力学习设计模式。 This site使用 synchronized
关键字,但我不明白它的作用。
在网上搜了一下,发现跟多线程和内存有点关系,但是我是机械工程师,不明白是什么意思。
谁能帮我理解线程和 synchronized
关键字?
最佳答案
C++ 中没有 synchronized
关键字。
不过,Java 中有一个,其中方法 it means the following two things :
- It is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
- When a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.
Similar rules apply to arbitrary blocks .
另外,我建议从同行评议的书籍中学习,而不是一些随意的非权威网站。
关于java - "synchronized"在 Java 中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7848471/