单例模式就不在这里详细介绍了,这里要了解的是如何使单例模式遇到多线程是安全的。
单例模式分为饿汉模式和懒汉模式。
饿汉模式就类在加载的时候就创建实例,当使用类的时候已经将对象创建好了
public class SingletonMode1 {
private static SingletonMode1 singletonMode1 = new SingletonMode1();
private SingletonMode1(){}
public static SingletonMode1 getInstance(){
return singletonMode1;
}
public static void main(String[] args){
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("Get hashCode: " + SingletonMode1.getInstance().hashCode());
}
};
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
Thread thread3 = new Thread(runnable);
Thread thread4 = new Thread(runnable);
Thread thread5 = new Thread(runnable);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
}
}
运行结果,获取的是同一个对象
懒汉模式是指在使用的时候才去创建对象实例,网上介绍多线程模式下怎样创建线程安全的单例模式很多,这里再回顾下,一步步去构架、完善,分析并解决问题。
最简单的单例模式
public class SingletonMode2 {
private SingletonMode2 mode2 = null;
private SingletonMode2(){}
public static SingletonMode2 getInstance(){
if(mode2 == null){
mode2 = new SingletonMode2();
}
return mode2;
}
}
该写法在单线程情况下没有问题的,那么在多线程模式下回怎样呢?
public class SingletonMode2 {
private static SingletonMode2 mode2 = null;
private SingletonMode2(){}
public static SingletonMode2 getInstance(){
try{
if(mode2 == null){
Thread.s