目录
一 实验
首先我们看一下单例模式的饿汉式多线程和懒汉式多线程 getInstance()获取的实例是否是同一个
现在开始
1.1 饿汉式多线程观察
package singletonMode;
public class SingletonHungry {
private static SingletonHungry singletonHungry = new SingletonHungry();
private SingletonHungry(){
System.out.println(this.getClass().getSimpleName()+"创建了");
}
public static SingletonHungry getInstance(){
System.out.println("SingletonHungry getInstance");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return singletonHungry;
}
}
package singletonMode;
public class Client {
public static void main(String[] args) {
System.out.println("main线程:这是单例模式");
//创建了一个线程,获取饿汉的实例
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("新线程:"+SingletonHungry.getInstance());
}
}).start();
System.out.println("main线程:"+SingletonHungry.getInstance());
}
}
结果
1.2 懒汉式多线程观察
package singletonMode;
public class SingletonLazy {
private static SingletonLazy singletonLazy = null;
private SingletonLazy(){
System.out.println(this.getClass().getSimpleName()+"创建了");
}
public static SingletonLazy getInstance(){
System.out.println("singletonLazy getInstance");
if(singletonLazy == null){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
singletonLazy = new SingletonLazy();
}
return singletonLazy;
}
}
package singletonMode;
public class Client {
public static void main(String[] args) {
System.out.println("main线程:这是单例模式");
//创建了一个线程,获取饿汉的实例
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("新线程:"+SingletonLazy.getInstance());
}
}).start();
System.out.println("main线程:"+SingletonLazy.getInstance());
}
}
结果:
可以看到懒汉式多线程创建的实例并不是同一个,单例模式只能有一个实例,所以现在要解决这个问题
二 单例模式解决线程安全问题
我们可以用 同步方法/同步代码块来解决懒汉式的多线程安全问题,但始终会带来效率问题
下面我们用更好地方式来实现
2.1 Holder的方式解决单例模式线程安全问题
package singletonMode;
/**
* 最终极的单例模式的写法
*/
public class SingletonHolder {
private static class SingletonInnerHolder{
private static SingletonHolder instance = new SingletonHolder();
}
private SingletonHolder(){
System.out.println("SingletonHolder 构造函数");
}
public static SingletonHolder getInstance(){
System.out.println("进入 SingletonHolder getInstance");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return SingletonInnerHolder.instance;
}
}
测试类
package singletonMode;
public class Client {
public static void main(String[] args) {
System.out.println("main线程:这是单例模式");
//创建了一个线程,获取饿汉的实例
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("新线程:"+SingletonHolder.getInstance());
}
}).start();
System.out.println("main线程:"+SingletonHolder.getInstance());
}
}
结果
ok了
总结:
饿汉式:线程安全,但是过早浪费资源 → 多个线程 getInstance()获取的实例是同一个
懒汉式:线程不安全,节约资源 → 不解决线程安全问题,多个线程 getInstance()获取的实例不是同一个
解决办法1:同步方法/同步代码块 → 始终会带来效率的问题
解决办法2:用Holder的方式创建一个内部类 → OK(单例模式 用这种好,推荐)