“同步”是什么意思?在Java中是什么意思?
我一直在努力学习设计模式。 此网站使用synchronized
关键字,但我没有了解它的作用。
我在网上搜索了一下,发现它与多线程和内存有些关系,但我是机械工程师,不明白这是什么意思。
有人可以帮助我理解线程和 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.
Can anybody please help me understand threads and the synchronized
keyword?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
C++ 中没有
synchronized
关键字。不过,Java 中有一个方法 意味着以下两件事:
类似的规则适用于任意块。
另外,我建议从同行评审的书籍中学习,而不是从一些任意的非权威网站上学习。
There is no
synchronized
keyword in C++.There is one in Java, though, where for methods it means the following two things:
Similar rules apply to arbitrary blocks.
Also, I recommend learning from a peer-reviewed book, not some arbitrary non-authoritative website.
在 (Java) 示例中,
意味着一次只能有一个线程能够访问 getInstance() 方法,以避免出现竞争情况。
In the (Java) example
means that only one thread at a time should be able to access the getInstance() method this to avoid a racing condition.
正如评论者已经指出的,synchronized 是一个 Java 关键字。
这意味着两个线程不能同时执行该方法,并且 JVM 负责强制执行。
在 C++ 中,您必须使用一些同步构造,例如临界区或互斥体。您可以查阅此。
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.