java | 固定大小的线程池 发表于 2023-01-01 分类于 java , 进阶 , 多线程 , 线程池 , ThreadPoolExecutor 阅读次数: Valine: newFixedThreadPool。 12345public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); } 特点 核心线程数 == 最大线程数「没有救急线程」 阻塞队列是无界的,可以放任意数量的任务 适用于任务量已知,相对耗时的任务 1234567891011121314151617181920212223package com.redisc;import lombok.extern.slf4j.Slf4j;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;@Slf4j(topic = "c.Test")public class Run { public static void main(String[] args) { ExecutorService pool = Executors.newFixedThreadPool(2); pool.execute(() -> { log.debug("1"); }); pool.execute(() -> { log.debug("2"); }); pool.execute(() -> { log.debug("3"); }); }} 输出 12323:15:59.050 [pool-1-thread-1] DEBUG c.Test - 123:15:59.050 [pool-1-thread-2] DEBUG c.Test - 223:15:59.057 [pool-1-thread-1] DEBUG c.Test - 3 请我喝杯咖啡吧~ 打赏 微信支付 支付宝