Java开发

Java线程池开发
贵鬼2024-10-17发布
28 0

ThreadPoolExecutor类

int poolSize = Runtime.getRuntime().availableProcessors();
//设置队列
BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(64);
//溢出报错策略
RejectedExecutionHandler policy = new ThreadPoolExecutor.AbortPolicy();
//可堵塞的线程池队列
ThreadPoolExecutor executorService = new ThreadPoolExecutor(poolSize, poolSize * 2, 180, TimeUnit.SECONDS,queue,policy);

策略:

ThreadPoolExecutor.AbortPolicy() 抛出异常

ThreadPoolExecutor.CallerRunsPolicy() 重试添加当前的任务,他会自动重复调用execute()方法

ThreadPoolExecutor.DiscardOldestPolicy() 抛弃旧的任务 

ThreadPoolExecutor.DiscardPolicy() 抛弃当前的任务