How to configure ThreadPoolExecutor in Java?

In Java, you can create a thread pool by configuring the constructor of ThreadPoolExecutor and setting parameters to control its behavior. Here is an example code demonstrating how to configure ThreadPoolExecutor:

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) {
        // 创建一个线程池,其中包含5个线程
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
            5, // 核心线程数
            10, // 最大线程数
            60, // 空闲线程存活时间
            TimeUnit.SECONDS, // 时间单位
            new LinkedBlockingQueue<Runnable>() // 阻塞队列
        );
        
        // 设置拒绝策略为直接抛出异常
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        
        // 执行任务
        executor.execute(new MyTask());
        
        // 关闭线程池
        executor.shutdown();
    }
}

class MyTask implements Runnable {
    @Override
    public void run() {
        System.out.println("Hello from MyTask!");
    }
}

In the example code above, we created a ThreadPoolExecutor object with a core thread pool size of 5, maximum thread pool size of 10, idle thread keep-alive time of 60 seconds, and a blocking queue of LinkedBlockingQueue. We then set the rejection policy to throw exceptions directly, executed a task, and finally shut down the thread pool. You can configure the parameters of ThreadPoolExecutor according to your own needs to meet different scenario requirements.

bannerAds