单例线程池工具类

单例线程池工具类


package com.xyhsoft.datagather.util;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @Describe: 单例线程池工具类
 * @Author: LYS
 * @DateTime: 2024/7/15 15:56
 */
@Slf4j
public class ThreadPoolUtil {
    //  防止指令重排,在new的过程中但还没有创建完成的过程中,其他线程进入拿到一个不完整的对象
    private static volatile ThreadPoolUtil INSTANCE;

    public static ThreadPoolExecutor threadPoolExecutor;
    private static final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();

    private ThreadPoolUtil() {
        int corePoolSize = Runtime.getRuntime().availableProcessors();
        int maximumPoolSize = corePoolSize * 2;
        //无界队列,适用于高并发处理大量任务
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(1);
        ThreadFactory threadFactory = new ThreadFactoryBuilder()
                .setNamePrefix("common-thread-pool")
                .setDaemon(true)
                .build();
        RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy();
        threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                90L,
                TimeUnit.SECONDS,
                workQueue,
                threadFactory,
                // 自定义拒绝策略手动执行任务
                (runnable, executor) -> {
                    if (!executor.isShutdown()) {
                        // 打印日志,说明任务被拒绝
                        log.warn("任务:" + runnable.toString() + "已经被拒绝");
                        log.warn("正在尝试手动执行任务");
                        // 尝试手动执行任务
                        try {
                            singleThreadExecutor.submit(runnable);
                        } catch (Throwable throwable) {
                            // 处理在手动执行过程中可能抛出的异常
                            log.error("手动执行任务异常:{},{}", runnable, throwable.getMessage());

                        }
                    }
                });
    }
/**
 * @Describe: 获取实例
 * @Author: LYS
 * @DateTime: 2024/7/15 15:56
 */
    public static ThreadPoolUtil getInstance() {
        if (INSTANCE == null) {
            synchronized (ThreadPoolUtil.class) {
                // 防止if和new之间非原子性操作进入别的线程
                if (INSTANCE == null) {
                    INSTANCE = new ThreadPoolUtil();
                }
            }
        }
        return INSTANCE;

    }
/**
 * @Describe: 关闭线程池
 * @Author: LYS
 * @DateTime: 2024/7/15 15:56
 */
    public static void shutdownThreadPool() {
        threadPoolExecutor.shutdown();
        try {
            if (!threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS)) {
                threadPoolExecutor.shutdownNow();
            }
        } catch (InterruptedException ie) {
            threadPoolExecutor.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }

    public boolean isShutdown() {
        return threadPoolExecutor.isShutdown();
    }
/**
 * @Describe: 重启线程池
 * @Author: LYS
 * @DateTime: 2024/7/15 15:56
 */
    public synchronized void restartThreadPool() {
        if (threadPoolExecutor != null && !threadPoolExecutor.isShutdown()) {
            threadPoolExecutor.shutdownNow();
            try {
                if (!threadPoolExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
                    System.out.println("Warning: Not all tasks completed before the restart.");
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        threadPoolExecutor = createThreadPool();
    }

    private ThreadPoolExecutor createThreadPool() {
        int corePoolSize = Runtime.getRuntime().availableProcessors();
        int maxPoolSize = corePoolSize * 2;
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>();
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNamePrefix("datagather-common-threadpool").build();
        //当拒绝策略生效时,不会开辟新的线程,而是使用调用者线程处理任务,会一直阻塞等待CallerRunsPolicy
        RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();
        return new ThreadPoolExecutor(corePoolSize, maxPoolSize, 60L, TimeUnit.SECONDS, workQueue, threadFactory, handler);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雨落纠纷

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值