单例模式之枚举创建

本文介绍了使用枚举类型实现Java单例模式,以此避免懒汉式和饿汉式的线程安全问题,并防止反射和序列化破坏单例。示例代码展示了如何创建一个线程安全且不可被非法实例化的单例类。
/**
 * @author 苏雪夜酒
 * @version 1.0
 * @date 2022/5/1 13:13
 */
public class SingletonEnum {
    public static void main(String[] args) {
        for (int i = 0; i < 30; i++) {
            new Thread(()->{
                Singleton_Enum instance = Singleton_Enum.INSTANCE;
                System.out.println(Thread.currentThread().getName() + "===" + instance.getName());
            }).start();
        }
    }
}
//单例模式 ---枚举 官方推荐,因为无论是懒汉式还是饿汉式,都会被反射和序列化破坏
enum Singleton_Enum{
    INSTANCE("单例");
    private String name;
    Singleton_Enum(String name){
        this.name = name;
    }
    public String getName(){
        return name;
    }
}

单例模式枚举实现线程池可利用枚举天然的特性。由于每个枚举项都是`public static final`的,所以枚举天然就是的,且枚举类型不能被继承,也不能有显式的构造函数,适合用于实现单例模式。以下为示代码: ```java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; // 定义一个枚举类型来实现线程池 enum ThreadPoolSingleton { // 枚举项,代表 INSTANCE; // 线程池对象 private final ExecutorService threadPool; // 枚举的构造函数,用于初始化线程池 ThreadPoolSingleton() { // 创建一个固定大小的线程池,这里设置为 10 个线程 threadPool = Executors.newFixedThreadPool(10); } // 获取线程池的方法 public ExecutorService getThreadPool() { return threadPool; } } // 测试类 public class Main { public static void main(String[] args) { // 获取线程池实 ExecutorService pool = ThreadPoolSingleton.INSTANCE.getThreadPool(); // 向线程池提交任务 pool.submit(() -> { System.out.println("Task is running on thread: " + Thread.currentThread().getName()); }); // 关闭线程池 pool.shutdown(); } } ``` 在上述代码中,`ThreadPoolSingleton`是一个枚举类型,其中的`INSTANCE`是枚举项,代表。在枚举的构造函数中,使用`Executors.newFixedThreadPool(10)`创建了一个固定大小为 10 的线程池。`getThreadPool`方法用于获取这个线程池实。在`Main`类的`main`方法中,通过`ThreadPoolSingleton.INSTANCE.getThreadPool()`获取线程池实,并向其提交了一个任务,最后关闭了线程池。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值