Java 中的同步方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7272538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:22:43  来源:igfitidea点击:

Synchronized Methods in Java

javamultithreadingsynchronized

提问by user919860

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?

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

回答by mre

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?

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

Right.

对。

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

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

回答by Jon7

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

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

回答by toto2

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.

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

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

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