我已经开始学习线程同步了。
同步方式:
public class Counter {
private static int count = 0;
public static synchronized int getCount() {
return count;
}
public synchronized setCount(int count) {
this.count = count;
}
}
同步块(synchronized block):
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
block ?
为什么 synchronized
block 比 synchronized
方法更好?
最佳答案
不是更好,只是不同。
当你同步一个方法时,你实际上是在同步到对象本身。在静态方法的情况下,您正在同步到对象的类。所以下面两段代码的执行方式相同:
public synchronized int getCount() {
// ...
}
这就像你写的一样。
public int getCount() {
synchronized (this) {
// ...
}
}
如果您想控制与特定对象的同步,或者您只想将方法的部分同步到该对象,则指定一个 synchronized
block 。如果在方法声明中使用 synchronized
关键字,它会将整个方法同步到对象或类。
关于java - 为什么同步块(synchronized block)比同步方法更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20906548/