What does “synchronized” mean in Java? [duplicate]

2019-03-18 01:12发布

This question already has an answer here:

I have been trying to learn design patterns. This site uses the synchronized keyword, but I don't understand what it does.

I searched on the net and found that it is somewhat related to multi-threading and memory, but I am a mechanical engineer and don't understand what that means.

Can anybody please help me understand threads and the synchronized keyword?

4条回答
我欲成王,谁敢阻挡
2楼-- · 2019-03-18 01:40

There is no synchronized keyword in C++.

There is one in Java, though, where for methods 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.

Also, I recommend learning from a peer-reviewed book, not some arbitrary non-authoritative website.

查看更多
爷、活的狠高调
3楼-- · 2019-03-18 01:43

As the commenters already pointed out, synchronized is a Java keyword.

It means that two threads cannot execute the method at the same time and the JVM takes care of enforcing that.

In C++, you will have to use some synchronization construct, like a critical section or a mutex. You can consult this.

查看更多
相关推荐>>
4楼-- · 2019-03-18 01:46

If one thread tries to read the data and other thread tries to update the same data, it leads to inconsistent state.

This can be prevented by synchronising access to the data. Use “synchronized” method:

 public synchronized void update()
 {
 …
 }
查看更多
霸刀☆藐视天下
5楼-- · 2019-03-18 01:52

In the (Java) example

public static synchronized Singleton getInstance()

means that only one thread at a time should be able to access the getInstance() method this to avoid a racing condition.

查看更多
登录 后发表回答