Singleton 单例模式

本文详细介绍了Java中单例模式的多种实现方式,包括饿汉式、懒汉式(线程不安全及线程安全)、静态内部类和枚举类方式。每种方式都分析了其实现原理和线程安全性,特别强调了双重检查锁定机制和volatile关键字在多线程环境中的作用。同时,静态内部类和枚举方式因其线程安全性和懒加载特性被推荐使用。
摘要由CSDN通过智能技术生成

1. 饿汉式

/**
 * 饿汉式
 * 类加载到内存后,就实例化一个单例,jvm保证线程安全
 * 简单使用,推荐使用!
 * 唯一的缺点:不管用到与否,类装载时就完成实例化
 */
public class Mgr01 {
    private static final Mgr01 INSTANCE = new Mgr01();

    private Mgr01(){}

    public static Mgr01 getInstance(){return INSTANCE;}

    public static void main(String[] args) {
        Mgr01 m1 = Mgr01.getInstance();
        Mgr01 m2 = Mgr01.getInstance();
        System.out.println(m1 == m2);
    }
}
/**
 * 也是饿汉式的一种实现方式
 */
public class Mgr02 {
    private static final Mgr02 INSTANCE;

    static {
        INSTANCE = new Mgr02();
    }

    private Mgr02(){}

    public static Mgr02 getInstance(){return INSTANCE;}

    public static void main(String[] args) {
        Mgr02 m1 = Mgr02.getInstance();
        Mgr02 m2 = Mgr02.getInstance();
        System.out.println(m1 == m2);
    }
}

2. 懒汉式

/**
 * 懒汉式
 * 虽然达到了按需初始化的目的,但是却又线程不安全的问题
 */
public class Mgr03 {
    private static Mgr03 INSTANCE;

    private Mgr03(){}

    public static Mgr03 getInstance(){
        if (INSTANCE == null){
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            INSTANCE = new Mgr03();
        }
        return INSTANCE;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                    System.out.println(Mgr03.getInstance().hashCode());
            }).start();
        }
    }
}
/**
 * 懒汉式
 * 虽然达到了按需初始化的目的,但是也带来了线程不安全的问题
 * 可以通过synchronized同步方法解决,但是效率下降了
 */
public class Mgr04 {
    private static Mgr04 INSTANCE;

    private Mgr04(){}

    public static synchronized Mgr04 getInstance(){
        if (INSTANCE == null){
            INSTANCE = new Mgr04();
        }
        return INSTANCE;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                System.out.println(Mgr04.getInstance().hashCode());
            }).start();
        }
    }
}
/**
 * 懒汉式的一种
 * 虽然达到按需初始化的目的,但是这种方式却不能使线程安全
 * 可以通过synchronized代码块解决,但是效率降低
 */
public class Mgr05 {
    private static Mgr05 INSTANCE;

    private Mgr05(){}

    public static Mgr05 getInstance(){
        if (INSTANCE == null){
            // 企图通过同步代码块的方式提高效率,但是这种做存在线程安全的问题
            synchronized (Mgr05.class){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                INSTANCE = new Mgr05();
            }
        }
        return INSTANCE;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                System.out.println(Mgr05.getInstance().hashCode());
            }).start();
        }
    }
}
/**
 * 懒汉式的一种,也称为双重检查机制
 * 达到了按需初始化的目的,同步双重检索确保了多线程的安全问题
 */
public class Mgr06 {
    /**
     * 这里一定要使用volatile,否则可能出现创建多个实例的情况
     * 原因:
     * volatile可以放置指令重排带来的多线程问题
     * 创建一个对象有三步骤:
     * 1. 分配对象的内存空间
     * 2. 初始化对象
     * 3. 设置instance指向刚分配的内存地址
     *
     * 但是在JIT编译器上,有可能2和3会发生重排序的问题
     * 假设A线程在创建实例过程中将instance指向内存空间后,此时install已经不为null,但是还没有初始化
     * 此时B线程在第一次检查instance是否为null时,此时处于非空状态,但是访问到的是一个未初始化的对象
     */
    private static volatile Mgr06 INSTANCE;

    private Mgr06(){}

    public static Mgr06 getInstance(){
        if (INSTANCE == null){
            synchronized (Mgr06.class){
                if (INSTANCE == null){
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    INSTANCE = new Mgr06();
                }
            }
        }
        return INSTANCE;
    }

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

3.静态内部类

/**
 * 静态内部类方式---也是一种懒加载方式,达到按需初始化的目的
 * JVM保证单例
 * 加载外部类时不会加载内部类,这样就实现了懒加载
 */
public class Mgr07 {
    private Mgr07(){}

    private static class Mgr07Holder{
        private final static Mgr07 INSTANCE = new Mgr07();
    }

    public static Mgr07 getInstance(){
        return Mgr07Holder.INSTANCE;
    }

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

4.枚举类方式

/**
 * 枚举方式
 * 不仅可以解决线程同步问题,也能够解决通过反射机制
 * 动态获取构造方法从而创建对象的
 */
public enum  Mgr08 {
    INSTANCE;

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                System.out.println(Mgr08.INSTANCE.hashCode());
            }).start();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值