任何人都可以通过一个例子告诉我同步方法优于synchronized块的优势吗?
我已经开始在线程中学习同步.
同步方法:
public class Counter {
private static int count = 0;
public static synchronized int getCount() {
return count;
}
public synchronized setCount(int count) {
this.count = count;
}
}
Run Code Online (Sandbox Code Playgroud)
同步块:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我什么时候应该使用Synchronized方法和Synchronized块?为什么Synchronized阻止比同步方法更好?