“同步”是什么意思?在Java中是什么意思?

发布于 2024-12-11 13:53:15 字数 250 浏览 0 评论 0原文

我一直在努力学习设计模式。 此网站使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

清秋悲枫 2024-12-18 13:53:15

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:

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

旧时浪漫 2024-12-18 13:53:15

在 (Java) 示例中,

public static synchronized Singleton getInstance()

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

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.

妄司 2024-12-18 13:53:15

正如评论者已经指出的,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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文