Java 中的同步方法
只是想检查一下以确保我理解这一点。同步方法不会创建线程,对吧?它只是确保当同一进程(即 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正确的。
正确的。
有关更多信息,请阅读同步方法。我还建议阅读Java 并发实践。
Right.
Right.
For more information, read Synchronized Methods. I also recommend reading Java Concurrency in Practice.
这基本上是正确的。调用同步方法不会产生新线程。当其他线程尝试为该对象的该实例调用任何其他同步方法时,它只会使其他线程阻塞。
要记住的关键是类的所有同步方法都使用相同的锁。
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.
是的。
同步块还有另一个重要作用:当线程进入同步块时,它会看到访问该块(或与同一锁同步的另一个块)的前一个线程对值所做的更改。
基本上在多核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.