NEW个对象 > JAVA > 当前页面

如何创建线程池?

2025-02-19 NEW个对象

1、通过ExecutorService

ExecutorService executor = Executors.newCachedThreadPool();
ExecutorService executor = Executors.newFixedThreadPool(nThreads);
ExecutorService executor = Executors.newSingleThreadExecutor();
ScheduledExecutorService executor = Executors.newScheduledThreadPool(corePoolSize);

2、使用 ThreadPoolExecutor 自定义线程池

ExecutorService executor = new ThreadPoolExecutor(
    corePoolSize(20), 
    maximumPoolSize(30), 
    keepAliveTime(60L), 
    unit(TimeUnit.SECONDS), 
    new LinkedBlockingQueue<Runnable>()
);

3、执行任务

executor.submit(() -> {
    // 任务逻辑
});

相关文章

推荐文章