“同步”是什么用Java表示?

“同步”是什么用Java表示?

问题描述:

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

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.

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

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

C ++中没有 synchronized 关键字。

There is no synchronized keyword in C++.

但是Java中有一个方法它表示以下两件事

There is one in Java, though, where for methods it means the following two things:



  • 不可能两个同步方法的调用对同一个对象进行交错。当一个线程正在为一个对象执行一个synchronized方法时,所有其他线程都会调用同一个对象的同步方法阻塞(暂停执行),直到第一个线程完成该对象为止。

  • 当一个synchronized方法退出,它会自动建立一个before-before关系,同时对同一个对象的同步方法进行任何后续调用。这可以保证对所有线程都可以看到对对象状态的更改。

类似的规则适用于任意块

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

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