线程池
package com.zh; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ThreadPoolTest implements Runnable { @Override public void run() { try { Thread.sleep(300); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(5); RejectedExecutionHandler handler = new ThreadPoolExecutor.DiscardPolicy(); // ThreadPoolExecutor threadPool = new ThreadPoolExecutor(5, 10, 60, // TimeUnit.SECONDS, queue,handler); ThreadPoolExecutor threadPool = new ThreadPoolExecutor(5, 10, 60, TimeUnit.SECONDS, queue); // 默认直接抛出异常 for (int i = 0; i < 16; i++) { threadPool.execute(new Thread(new ThreadPoolTest(), "Thread".concat(i + ""))); System.out.println("线程池中活跃的线程数: " + threadPool.getPoolSize()); if (queue.size() > 0) { System.out.println("----------------队列中阻塞的线程数" + queue.size()); } } threadPool.shutdown(); } }
运行过程
刚开始都是在创建新的线程,达到核心线程数量5个后,新的任务进来后不再创建新的线程,而是将任务加入工作队列,任务队列到达上线5个后,新的任务又会创建新的线程,直到达到线程池最大的线程数量10个,后面的任务则根据配置的饱和策略来处理。我们这里没有具体配置,使用的是默认的配置AbortPolicy:直接抛出异常。