如何实现单例模式线程池

在Java中,实现一个单例模式的线程池,可以使用ExecutorService接口,下面是具体代码:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) {
        // 获取线程池实例
        ExecutorService threadPool = SingletonThreadPool.getInstance();

        // 在这里使用线程池执行任务
        for (int i = 0; i < 10; i++) {
            final int taskNumber = i;
//            threadPool.execute(()->{
//                System.out.println("Task " + taskNumber + " is running on thread " + Thread.currentThread().getName());
//            });
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("Task " + taskNumber + " is running on thread " + Thread.currentThread().getName());
                }
            });
        }
        // 关闭线程池
        threadPool.shutdown();
    }
}

class SingletonThreadPool{
    private static ExecutorService instance;

    private SingletonThreadPool(){
        // 私有构造方法,防止外部直接实例化
    }

    public static synchronized ExecutorService getInstance(){
        if(instance == null){
            instance = Executors.newFixedThreadPool(5);
        }
        return instance;
    }
}

在这个例子中,SingletonThreadPool类采用了懒汉式的单例模式,确保只有在需要时才创建线程池。通过getInstance方法获取线程池实例,并使用execute方法提交任务。最后,在程序结束时,调用shutdown方法关闭线程池。

但需要注意的是,这只是一个简单的示例。在实际应用中,可能还需要根据具体的需求调整线程池的配置参数,比如线程池的大小、任务队列的类型等。同时也建议自己构造线程池,不使用现有的4种线程池类型,避免请求(任务)的堆积或大量线程的创建,从而避免OOM。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值