“同步”在Java中意味着什么?

What does “synchronized” mean in Java?

本问题已经有最佳答案,请猛点这里访问。

我一直在努力学习设计模式。这个网站使用synchronized关键字,但我不明白它的作用。

我在网上搜索,发现它与多线程和内存有些关系,但我是一个机械工程师,不明白这意味着什么。

有人能帮我理解线程和synchronized关键字吗?


C++中没有EDCOX1的0个关键字。

在Java中有一个,但是对于方法来说,它意味着以下两件事:

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

类似的规则适用于任意块。

另外,我建议从同行评议的书中学习,而不是一些武断的非权威网站。


在(Java)示例中

1
public static synchronized Singleton getInstance()

意味着一次只能有一个线程能够访问getInstance()方法,以避免出现争用情况。


正如评论家已经指出的,同步是一个Java关键字。

这意味着两个线程不能同时执行该方法,而JVM负责执行该方法。

在C++中,您必须使用一些同步构造,例如临界区或互斥体。你可以参考这个。


如果一个线程试图读取数据和其他线程线程试图更新相同的数据,它导致状态不一致。

这可以通过同步访问来防止数据。使用"同步"方法:

1
2
3
4
 public synchronized void update()
 {
 …
 }