java练习

单例模式

 

import java.io.*;

class singleton {
    
    Integer y = 2;
    
    private static volatile singleton instance = null;
    
    public static singleton getInstance() {
        if (instance == null) {
            synchronized(singleton.class) {
                if (instance == null) {
                    instance = new singleton();
                }
            }
        }
        return instance;
    }
    
    public singleton(){}
}

class test  
{
    
    public static void main (String[] args) throws java.lang.Exception
    {
        singleton x = singleton.getInstance();
        System.out.print(x.y);
    }
}

 

suqiandeMacBook-Pro:~/Tmp$ javac test.java
suqiandeMacBook-Pro:~/Tmp$ java test
2

suqiandeMacBook-Pro:~/Tmp$

 

posted on 2021-11-19 17:49  出发的兰彻  阅读(10)  评论(0编辑  收藏  举报

导航