class Single {
private Single() {
};
static Object obj = new Object();
private static Single s = null;
/**
* 用同步代码块,不需要每次都判断锁,效率高
*/
public static Single getSingle1() {
if (s == null) {
synchronized (obj) {
if (s == null) {
s = new Single();
}
}
}
return s;
}
/**
* 用同步方法,每次都需要判断锁,效率低
*/
public static synchronized Single getSingle2() {
if (s == null) {
s = new Single();
}
return s;
}
}
多线程下的懒汉模式,同步代码块和同步方法
最新推荐文章于 2022-02-19 13:26:30 发布