victory的博客

长安一片月,万户捣衣声

0%

单例模式 | 双重检验锁方式实现单例模式

参考资料

package SingletonTest;

class Singleton{
    private volatile static Singleton instance;
    
    private Singleton(){
        
    }
    
    public static Singleton getInstance(){
        if(instance == null){
            synchronized (Singleton.class) {
                if(instance == null){
                    instance = new Singleton();
                }
                //instance = new Singleton();
            }
        }
        return instance;
    }
}

public class MyThread extends Thread{
    @Override
    public void run(){
        System.out.println(Singleton.getInstance().hashCode());
    }
    
    public static void main(String[] args){
        MyThread[] myThread = new MyThread[10];
        for(int i=0;i<myThread.length;i++){
            myThread[i] = new MyThread();
        }
        
        for(int i=0;i<myThread.length;i++){
            myThread[i].start();
        }
    }
}

双重锁的运行结果:

1156205522
1156205522
1156205522
1156205522
1156205522
1156205522
1156205522
1156205522
1156205522
1156205522

去掉第二重锁的运行结果(产生了多例):

1700548907
1486202908
1486202908
1700548907
1486202908
1486202908
1700548907
1486202908
1486202908
1700548907