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.
这篇关于为什么同步块比同步方法更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么同步块比同步方法更好?
基础教程推荐
- 存储 20 位数字的数据类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
