Java 多线程之自定义线程池(ThreadPool)使用方法
    		       		warning:
    		            这篇文章距离上次修改已过430天,其中的内容可能已经有所变动。
    		        
        		                
                
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
 
public class CustomThreadPoolExample {
    public static void main(String[] args) {
        // 创建一个自定义线程池
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                2, // 核心线程数
                5, // 最大线程数
                1000, // 空闲时间(1000毫秒)
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(3), // 任务队列的容量
                new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略
        );
 
        // 运行任务
        for (int i = 0; i < 10; i++) {
            threadPool.execute(() -> {
                System.out.println("任务正在执行,线程:" + Thread.currentThread().getName());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
 
        // 关闭线程池
        threadPool.shutdown();
    }
}这段代码创建了一个自定义的线程池,设置了核心线程数为2,最大线程数为5,空闲时间为1000毫秒,使用了一个容量为3的链接队列,并使用了CallerRunsPolicy拒绝策略。然后提交了10个简单的任务,每个任务执行时会打印信息和线程名称,并休眠1000毫秒。最后,代码关闭了线程池。这个例子展示了如何根据实际需求定制线程池的参数。
评论已关闭