Java中ThreadPoolExecutor基本使用

June 06, 2025 / Nick / 3阅读 / 0评论 / 分类: 技术

直接上代码.使用的东西放在注释了

Main.java


public class Main {

    public static void main(String[] args) {

        int cpuCores = Runtime.getRuntime().availableProcessors();
        System.out.println("当前CPU核心数为:" + cpuCores);

        // 线程池参数 参数说明参考: https://www.cnblogs.com/linjiqin/p/17083542.html
        // 最佳线程数 =1 +(I/O 耗时 / CPU 耗时)
        // CPU密集型, 最佳线程数=CPU 核数 +1
        // IO密集型,最佳线程数 =CPU 核数 * 2
        // IO密集型和CPU密集型交叉运行,最佳线程数 =CPU 核数 * [ 1 +(I/O 耗时 / CPU 耗时)]

        // 核心线程数,看CPU核数来设置,核心数+1
        int coreThreadCount = cpuCores + 1;
        // 最大线程数
        int maxThreadCount = cpuCores * 2 + 1;
        // 线程存活时间,我这里是3000毫秒
        int keepAlive = 3000;
        // 存活时间单位
        TimeUnit timeUnit = TimeUnit.MILLISECONDS;
        // 线程阻塞队列, 这里测试, 写了队列长度为 2
        BlockingQueue<Runnable> runnableBlockingQueue = new LinkedBlockingQueue<Runnable>(2);
        // 线程创建工厂,用的默认的
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        // 自定义拒绝策略,这里设置的 拒绝之后三秒后尝试加入
        RejectedExecutionHandler handler = (r, executor) -> {
            // 自定义拒绝策略
            // 等三秒后尝试加入
            System.out.println("线程池满了,等三秒后加入");
            try {
                Thread.sleep((long)(Math.random() * 3000));
            } catch (InterruptedException e) {
                System.out.println("设置拒绝策略等待出现异常:" + e.getMessage());
            }
            executor.execute(r);

        };

        // 初始化线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                coreThreadCount,
                maxThreadCount,
                keepAlive,
                timeUnit,
                runnableBlockingQueue,
                threadFactory,
                handler);

        // 执行任务
        int taskCount = 100;
        for (int i = 0; i < taskCount; i++) {

            int finalI = i;
            try {
                threadPoolExecutor.execute(() -> {
                        System.out.println( "线程: " + Thread.currentThread().getName() + " 处理任务id" + finalI);
                    try {
                        Thread.sleep((long)(Math.random() * 500));
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println("处理完毕: 线程: " + Thread.currentThread().getName() + " 处理任务id" + finalI);

                });
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }

        System.out.println("线程池大小: " + threadPoolExecutor.getPoolSize());
        System.out.println("线程池核心线程大小: " + threadPoolExecutor.getCorePoolSize());
        System.out.println("线程池最大线程数: " + threadPoolExecutor.getMaximumPoolSize());
        System.out.println("线程池任务数: " + threadPoolExecutor.getTaskCount());
        System.out.println("线程池活跃数?: " + threadPoolExecutor.getActiveCount());

        int threadCount = Thread.activeCount();
        System.out.println("当前线程数:" + threadCount);

        System.out.println("任务分配完毕,等待执行");

        // 把线程池嘎了
        System.out.println("把线程池嘎了");
        threadPoolExecutor.shutdown();
        System.out.println("线程池嘎完了");


    }

}
  

文章作者:Nick

文章链接:https://nick.xin//2025/06/06/javazhong-threadpoolexecutorji-ben-shi-yong

版权声明:本博客所有文章除特别声明外,均采用CC BY-NC-SA 4.0 许可协议,转载请注明出处!


评论