使用 ThreadPoolExecutor 创建多线程工具类

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPoolUtils {

    private ThreadPoolExecutor pool = null;

    static Integer num = 0;


    /**
     * 获取CPU核数
     */
    private static final int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors();
    private static final int MAXIMUM_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 5;
    /**
     * 阻塞队列大小
     */
    private  static  final int MAX_TASK_SIZE =  Integer.MAX_VALUE;

    /**
     * IO密集线程池配置
     * @return
     */
    public  ThreadPoolExecutor getIOInstance( ){
        return  getNewInstance(CORE_POOL_SIZE * 2 + 1 , MAXIMUM_POOL_SIZE,"IO",MAX_TASK_SIZE);
    }
    /**
     * CUP密集线程池配置
     * @return
     */
    public  ThreadPoolExecutor getCUPInstance( ){
        return  getNewInstance(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE,"CUP",MAX_TASK_SIZE);
    }
    /**
     * 获取对象
     * @param corePoolSize 核心线程数量
     * @param poolName 线程池名称
     * @param maxThreadSize 最大线程数
     * @param maxTaskSize 最大阻塞任务数
     * @return
     */
    public ThreadPoolExecutor getNewInstance(int corePoolSize,int maxThreadSize,String poolName,int maxTaskSize){

        pool = createPool(corePoolSize,maxThreadSize,poolName,maxTaskSize);

        if(pool==null){
            throw new NullPointerException();
        }else{
            return pool;
        }
    }

    /**
     * 创建线程池
     * @param corePoolSize 核心线程数量
     * @param poolName 线程池名称
     * @param maxThreadSize 最大线程数
     * @param maxTaskSize 最大阻塞任务数
     * @return
     */
    private ThreadPoolExecutor createPool(int corePoolSize,int maxThreadSize,String poolName,int maxTaskSize){

        return new ThreadPoolExecutor(corePoolSize,maxThreadSize,0,
                TimeUnit.SECONDS,new LinkedBlockingQueue<>(maxTaskSize),
                new CustomThreadFactory(poolName),
                new RejectedExecutionHandlerImpl());
    }

    /**
     * 线程工厂
     * 给线程命名
     */
    private class CustomThreadFactory implements ThreadFactory {

        private final String poolName;

        public CustomThreadFactory(String poolName){
            this.poolName = poolName;
        }

        private AtomicInteger count = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            String nowThreadName = "";
            nowThreadName = poolName + count.addAndGet(1);
            t.setName(nowThreadName);
            return t;
        }
    }

    /**
     * 自定义拒绝策略
     */
    private class RejectedExecutionHandlerImpl implements RejectedExecutionHandler {

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            try{
                System.out.println("重回队列");
                executor.getQueue().put(r);
            }catch (Exception e){

            }
        }
    }

    public static void main(String[] args){
        ThreadPoolExecutor executor = new ThreadPoolUtils().getNewInstance(3,8,"test",5);

        for (int i = 0;i<20;i++){
            System.out.println("提交第"+i+"个任务");
            executor.execute(()->{
                try {
                    System.out.println(Thread.currentThread().getName());
                    TimeUnit.SECONDS.sleep(10);
                    synchronized (num){
                        System.out.println("数字为:"+num++);
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            System.out.println("提交第"+i+"个任务成功");
        }
        System.out.println("结束");
    }
}

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,您的问题是如何使用 ThreadPoolExecutor 封装一个 Java 工具类,以便在项目中使用。 首先,让我们快速了解一下 ThreadPoolExecutorThreadPoolExecutorJava 提供的一个线程池实现,可以用于管理多个线程的执行。当我们需要运行大量的且相对较短的任务时,使用线程池可以减少线程的创建和销毁操作,提高性能。ThreadPoolExecutor 可以设置核心线程数、最大线程数、任务队列、拒绝策略等参数,以便满足我们的需求。 下面是封装 ThreadPoolExecutor工具类示例代码: ``` import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ThreadPoolUtils { private static ThreadPoolExecutor threadPoolExecutor; public static void initThreadPool() { int corePoolSize = 5; // 核心线程数 int maximumPoolSize = 10; // 最大线程数 long keepAliveTime = 60; // 非核心线程等待新任务的最长时间 TimeUnit unit = TimeUnit.SECONDS; ArrayBlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(100); // 任务队列,可根据实际情况调整大小 threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); } public static void executeTask(Runnable task) { if (threadPoolExecutor == null) { initThreadPool(); } threadPoolExecutor.execute(task); } } ``` 上面的代码定义了一个 ThreadPoolUtils 类,其中 initThreadPool() 方法用于初始化线程池,executeTask(Runnable task) 方法用于向线程池中添加任务。在使用时,可通过调用 executeTask() 方法来执行任务。 使用示例: ``` public class Test { public static void main(String[] args) { Thread task1 = new Thread(() -> { System.out.println("Task 1 is running."); }); Thread task2 = new Thread(() -> { System.out.println("Task 2 is running."); }); ThreadPoolUtils.executeTask(task1); ThreadPoolUtils.executeTask(task2); } } ``` 在上面的示例中,我们创建了两个线程,然后通过 ThreadPoolUtils.executeTask() 方法将它们添加到线程池中。 希望这个例子能够解决您的问题。如果您有任何其他问题,请随时问我。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值