Why is synchronized block better than synchronized method?(为什么同步块比同步方法更好?)
问题描述
我已经开始学习线程同步了.
I have started learning synchronization in threading.
同步方式:
public class Counter {
private static int count = 0;
public static synchronized int getCount() {
return count;
}
public synchronized setCount(int count) {
this.count = count;
}
}
同步块:
public class Singleton {
private static volatile Singleton _instance;
public static Singleton getInstance() {
if (_instance == null) {
synchronized(Singleton.class) {
if (_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
}
什么时候应该使用 synchronized
方法和 synchronized
块?
When should I use synchronized
method and synchronized
block?
为什么 synchronized
块比 synchronized
方法更好?
Why is synchronized
block better than synchronized
method ?
推荐答案
不是更好,只是不同.
当你同步一个方法时,你实际上是在同步到对象本身.在静态方法的情况下,您正在同步到对象的类.所以下面两段代码的执行方式相同:
When you synchronize a method, you are effectively synchronizing to the object itself. In the case of a static method, you're synchronizing to the class of the object. So the following two pieces of code execute the same way:
public synchronized int getCount() {
// ...
}
这就像你写的一样.
public int getCount() {
synchronized (this) {
// ...
}
}
如果您想控制与特定对象的同步,或者您只想将方法的部分同步到该对象,则指定一个 synchronized
块.如果在方法声明中使用 synchronized
关键字,它会将整个方法同步到对象或类.
If you want to control synchronization to a specific object, or you only want part of a method to be synchronized to the object, then specify a synchronized
block. If you use the synchronized
keyword on the method declaration, it will synchronize the whole method to the object or class.
这篇关于为什么同步块比同步方法更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么同步块比同步方法更好?


- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 转换 ldap 日期 2022-01-01
- 获取数字的最后一位 2022-01-01