JUC_07

1、单例模式。
饿汉式

点击查看代码
package org.li;

public class LazyDemo {
    private LazyDemo(){
        
    }
    private final static LazyDemo lazyDemo= new LazyDemo();
    public static LazyDemo getInstance(){
        return lazyDemo;
    }
}

懒汉式
点击查看代码
package org.li;

public class LazyDemo {
    private LazyDemo(){

    }
    private volatile static LazyDemo lazyDemo;
    public static LazyDemo getInstance(){
        if(lazyDemo==null){
            synchronized(LazyDemo.class){
                if(lazyDemo==null){
                    lazyDemo=new LazyDemo();
                }
            }
        }

        return lazyDemo;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 2000; i++) {
            new Thread(()->{
                LazyDemo instance = getInstance();
                System.out.println(instance);
            }).start();
        }
    }
}

静态内部类
点击查看代码
package org.li;

public class StaticInnerClass {
    private StaticInnerClass(){};
    public  static StaticInnerClass getInstance(){
        return Inner.staticInnerClass;
    } 
    public static class Inner{
        private static final StaticInnerClass staticInnerClass = new StaticInnerClass();
    }
}

2、枚举 本身是一个类 实现单例
点击查看代码
package org.li;

public enum EnumInstance {
    INSTANCE;
    public static EnumInstance getInstance(){
        return INSTANCE; 
    }
}

posted @ 2025-04-17 20:08  黑影五  阅读(7)  评论(0)    收藏  举报