package com.demo;
/*
* 单例模式
* 下的线程锁问题
*/
public class SingleTHreadLock {
}
// ----------懒汉式(迟加载)
class Single1 {
private static Single1 s = null;
private Single1() {
}
// -------------------------使用同步函数的方式,效率比较低,因为同步外的线程每一次都需要判断锁
public static synchronized Single1 getInstance1() {
if (s == null) {
s = new Single1();
}
return s;
}
// ----------------------使用双重判断,效率更高
public static Single1 getInstance2() {
if (s == null) {
synchronized (Single1.class) {
if (s == null) {
s = new Single1();
}
}
}
return s;
}
}
// -----------饿汉式
class Single2 {
private static Single2 s = new Single2();
private Single2() {
}
public Single2 getInstance() {
return s;
}
}
单例模式 下的线程锁问题
最新推荐文章于 2019-07-12 15:22:38 发布