/**
* 饿汉式:加载类的时候,就创建了对象
*/
public class Ehanshi {
// 创建对象
private static Ehanshi ehanshi = new Ehanshi();
// 无参构造
private Ehanshi() {
}
public Ehanshi getInstance() {
return ehanshi;
}
}
public class LhanShi {
/**
* 懒汉式的多里会遇到线程安全问题
*
* 有可能会获取到多个实例
*/
private static LhanShi lhanShi;
private LhanShi() {
}
public static LhanShi getInstance() {
if (lhanShi == null) {
try {
// 线程休眠
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
};
lhanShi = new LhanShi();
}
return lhanShi;
}
public static void main(String[] args) {
// 开辟10条线程
for (int i= 0;i<10;i++){
new Thread(new Runnable() {
@Override
public void run() {
LhanShi instance = LhanShi.getInstance();
System.out.println(instance.hashCode());
}
}).start();
}
}
}
既然懒汉式会出问题,如何解决懒汉式的线程同步问题? /**
* 需要用的时候,才会创建对象
*/
public class LhanShi {
/**
* 懒汉式的多里会遇到线程安全问题
*
* 有可能会获取到多个实例
*/
private static LhanShi lhanShi;
private LhanShi() {
}
/**
* synchronized:方法使用synchronized修饰,此方法同一时间只允许一条线程访问
* @return
*/
public synchronized static LhanShi getInstance() {
if (lhanShi == null) {
try {
// 线程休眠
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
};
lhanShi = new LhanShi();
}
return lhanShi;
}
public static void main(String[] args) {
// 开辟10条线程
for (int i= 0;i<10;i++){
new Thread(new Runnable() {
@Override
public void run() {
LhanShi instance = LhanShi.getInstance();
System.out.println(instance.hashCode());
}
}).start();
}
}
}