单例对象

饿汉式:不支持延迟加载

private static OneSingle oneSingle = new OneSingle();
public static OneSingle getInstance(){
    return oneSingle;
}

懒汉式:

getInstance方法必须添加 同步关键字,运行效率比较慢,支持懒加载。
同步关键字:防止多线程初始多个对象。

public class TwoSingle {
private static TwoSingle twoSingle = null;

public static synchronized TwoSingle getInstance() {
if(null == twoSingle){
System.out.println("初始对象!");
twoSingle = new TwoSingle();
}
return twoSingle;
}

public static void main(String[] args){
/**
TwoSingle twoSingle = TwoSingle.getInstance();
TwoSingle twoSingle2 = TwoSingle.getInstance();
System.out.println(twoSingle == twoSingle2);
*/
for(int i=0,len=150;i<len;i++){
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
TwoSingle.getInstance();
}
});
thread.start();
}
}
}

3、双重锁判断机制(DCL模式 Double Check Lock)

volatile:在多核系统中,对应L1,L2级的高速缓存,当对象被修改时,其他CPU的高速缓存,可以见其修改的值。
    private static volatile ThreeSingle threeSingle=null;


    public static ThreeSingle getInstance(){

        if(threeSingle==null){
            synchronized (ThreeSingle.class){
                System.out.println(Thread.currentThread().getId()+",,,"+System.currentTimeMillis()+" init object!");
                threeSingle = new ThreeSingle();
            }
        }
        return threeSingle;
    }

    public static void main(String[] args){

        for(int i=0,len=1500;i<len;i++){
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    ThreeSingle.getInstance();
                }
            });
            thread.start();
        }
    }

4、内部类

private  FourSingle(){}

    private static class SingleClass {
        private static final FourSingle fourSingle = new FourSingle();
    }

    public static FourSingle getInstance(){
        return SingleClass.fourSingle;
    }


    public static void main(String[] args){

        for(int i=0,len=150;i<len;i++){
            Thread thread = new Thread(new Runnable() {
                public void run() {
                    System.out.println(FourSingle.getInstance().hashCode());
                }
            });
            thread.start();
        }
    }
原文地址:https://www.cnblogs.com/liuwd/p/10833339.html