创建自定义线程池推荐ThreadPoolExecutor
public ThreadPoolExecutor(int corePoolSize, // 核心线程池大小 int maximumPoolSize, // 最大线程池 long keepAliveTime, // 没人用的时候保留的时间 TimeUnit unit, // 时间单位 BlockingQueue<Runnable> workQueue, // 阻塞队列 ThreadFactory threadFactory, // 线程工厂 RejectedExecutionHandler handler // 拒绝策略 ) { if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0) throw new IllegalArgumentException(); if (workQueue == null || threadFactory == null || handler == null) throw new NullPointerException(); this.acc = System.getSecurityManager() == null ? null : AccessController.getContext(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; }
自定义线程池
import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ThreadDemo { public static void main(String[] args) { // 自定义线程池 ThreadPoolExecutor threadPool = new ThreadPoolExecutor( 3, // 核心线程池大小为3 6, // 最大线程池为6,可以优化成CPU的核心数,Runtime.getRuntime().availableProcessors() 2, // 没人用的时候保留的时间为2 TimeUnit.SECONDS, // 时间单位为秒 new LinkedBlockingQueue(3), // 阻塞队列大小为3 Executors.defaultThreadFactory(), // 默认的线程工厂 new ThreadPoolExecutor.AbortPolicy()); // 拒绝策略,有4中可以根据需求选择 // 四种拒绝策略 /* 当最大核心线程满了,队列满了,下面4种拒绝策略会有不同的处理方式 new ThreadPoolExecutor.AbortPolicy(); // 调用任务不处理,直接抛出异常 new ThreadPoolExecutor.CallerRunsPolicy(); // 调用任务从哪里来去那里去,不会抛出异常 new ThreadPoolExecutor.DiscardPolicy(); // 调用任务直接丢弃,不会抛出异常 new ThreadPoolExecutor.DiscardOldestPolicy(); // 调用任务会和最早使用的线程竞争,不会抛出异常 */ for (int i = 1; i < 20; i++) { threadPool.execute(() -> { System.out.println("当前线程池名称:" + Thread.currentThread().getName()); }); } } }
来源:狂神说Java
转载:https://www.kuangstudy.com/course?cid=1