IO密集型任务设置线程池参考

61 阅读1分钟

import java.util.concurrent.*;

public class ThreadPoolConfig {

public static void main(String[] args) {
    // CPU的核心数
    int coreCount = Runtime.getRuntime().availableProcessors();
    
    // 核心线程数设置为CPU核心数的2倍
    int corePoolSize = coreCount * 2;

    // 最大线程数设置为核心线程数的2倍
    int maximumPoolSize = corePoolSize * 2;

    // 当线程数大于核心线程数时,多余空闲线程的存活时间
    long keepAliveTime = 60L;

    // 创建工作队列,大小可以根据实际情况调整
    BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(100);

    // 创建线程工厂,可自定义线程名字等信息
    ThreadFactory threadFactory = Executors.defaultThreadFactory();

    // 创建拒绝策略,此处使用CallerRunsPolicy
    RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();

    // 创建线程池
    ThreadPoolExecutor executor = new ThreadPoolExecutor(
            corePoolSize,
            maximumPoolSize,
            keepAliveTime,
            TimeUnit.SECONDS,
            workQueue,
            threadFactory,
            handler
    );

    // 使用线程池...
    // 例如,提交任务
    // executor.execute(任务);

    // 在程序结束时关闭线程池
    // executor.shutdown();
}

}