Java 中的同步方法

发布于 2024-12-02 06:39:15 字数 87 浏览 1 评论 0原文

只是想检查一下以确保我理解这一点。同步方法不会创建线程,对吧?它只是确保当同一进程(即 JVM)中的一个线程正在使用该方法时,没有其他线程正在调用该方法,对吗?

Just wanted to check to make sure that I understand this. A synchronized method doesn't create a thread, right? It only makes sure that no other thread is invoking this method while one thread within the same process (ie the JVM) is using it, right?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

慕烟庭风 2024-12-09 06:39:15

同步方法不会创建线程,对吧?

正确的。

它仅确保在执行此操作时没有其他线程调用此方法
同一进程(即 JVM)中的一个线程正在使用它,对吗?

正确的。

有关更多信息,请阅读同步方法。我还建议阅读Java 并发实践

A synchronized method doesn't create a thread, right?

Right.

It only makes sure that no other thread is invoking this method while
one thread within the same process (ie the JVM) is using it, right?

Right.

For more information, read Synchronized Methods. I also recommend reading Java Concurrency in Practice.

千年*琉璃梦 2024-12-09 06:39:15

这基本上是正确的。调用同步方法不会产生新线程。当其他线程尝试为该对象的该实例调用任何其他同步方法时,它只会使其他线程阻塞。

要记住的关键是类的所有同步方法都使用相同的锁。

That's mostly correct. Calling a synchronized method does not spawn a new thread. It just makes other threads block when they try to call any other synchronized method for that instance of that object.

The key thing to remember is that all synchronized methods of a class use the same lock.

暗喜 2024-12-09 06:39:15

是的。

同步块还有另一个重要作用:当线程进入同步块时,它会看到访问该块(或与同一锁同步的另一个块)的前一个线程对值所做的更改。

基本上在多核CPU上,每个线程在其核心上都有自己的内存缓存:每个核心都有相同变量的副本,它们的值在每个核心上可能不同。
当存在同步操作时,JVM 确保将变量值从一个内存缓存复制到另一个内存缓存。然后,进入同步块的线程会看到前一个线程“更新”的值。

正如 mre 所建议的,如果您确实想了解多线程并学习最佳实践,《Java 并发实践》是一个很好的参考。

Yes.

There is another important role for synchronized blocks too: when a thread enters a synchronized block it sees the changes to the values made by the previous thread that accessed that block (or another block synchronized with the same lock).

Basically on a multicore cpu, each thread as its own memory cache on its core: each core has copies of the same variables, their values might be different on each core.
When there is a synchronized operation, the JVM makes sure that the variable values are copied from one memory cache to the other. A thread entering a synchronzed block then sees the values "updated" by a previous thread.

As suggested by mre, Java Concurrency in Practice is a good reference if you really want to understand multithreading and learn best practices.

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