0
点赞
收藏
分享

微信扫一扫

【JavaScript 漫游】【041】File 对象、FileList 对象、FileReader 对象

夹胡碰 03-27 15:30 阅读 3

饿汉式单例(静态常量初始化)

// 饿汉式单例,线程安全,类加载时初始化实例
public class SingletonHungry {
    // 使用私有构造函数防止外部实例化
    private SingletonHungry() {}

    // 类加载时创建单例对象并赋值给静态final变量,保证线程安全
    private static final SingletonHungry INSTANCE = new SingletonHungry();

    // 提供公共的静态方法返回唯一的实例
    public static SingletonHungry getInstance() {
        return INSTANCE;
    }
}

懒汉式单例(线程不安全)

// 懒汉式单例(非线程安全版)
public class SingletonLazyUnsafe {
    private static SingletonLazyUnsafe instance;

    private SingletonLazyUnsafe() {}

    // 第一次调用getInstance方法时创建实例,但这种方法在多线程环境下不安全
    public static SingletonLazyUnsafe getInstance() {
        if (instance == null) {
            instance = new SingletonLazyUnsafe();
        }
        return instance;
    }
}

懒汉式单例(线程安全,同步方法)

// 懒汉式单例(线程安全版,同步方法)
public class SingletonLazySafeSyncMethod {
    private static SingletonLazySafeSyncMethod instance;

    private SingletonLazySafeSyncMethod() {}

    // 使用synchronized关键字同步方法以确保线程安全
    public static synchronized SingletonLazySafeSyncMethod getInstance() {
        if (instance == null) {
            instance = new SingletonLazySafeSyncMethod();
        }
        return instance;
    }
}

懒汉式单例(线程安全,双重检查锁定)

// 懒汉式单例(线程安全版,双重检查锁定DCL - Double Checked Locking)
public class SingletonLazySafeDCL {
    private volatile static SingletonLazySafeDCL instance; // 使用volatile防止指令重排序

    private SingletonLazySafeDCL() {}

    public static SingletonLazySafeDCL getInstance() {
        if (instance == null) {
            synchronized (SingletonLazySafeDCL.class) {
                // 第二次检查,只有在null的情况下才会进入下面的new操作
                if (instance == null) {
                    instance = new SingletonLazySafeDCL();
                }
            }
        }
        return instance;
    }
}

在上述代码中,饿汉式单例在类被加载时就完成了实例化,所以它是线程安全的;而懒汉式单例则是在第一次调用getInstance方法时才进行实例化,为了解决线程安全问题,懒汉式单例可以通过同步方法或双重检查锁定机制来确保多线程环境下的安全性。其中,双重检查锁定(DCL)是常用的优化手段,它既保证了线程安全,也避免了每次都进行同步操作带来的性能损耗。

举报

相关推荐

0 条评论