线程池的创建
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler)
corePoolSize:线程池核心线程数量
maximumPoolSize:线程池最大线程数量
keepAliverTime:当活跃线程数大于核心线程数时,空闲的多余线程最大存活时间
unit:存活时间的单位
workQueue:存放任务的队列
handler:超出线程范围和队列容量的任务的处理程序
实现原理
代码测试
public class ThreadPooltest implements Runnable { @Override public void run() { try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(6); ThreadPoolExecutor threadPool = new ThreadPoolExecutor(5, 9, 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(); } }
执行结果:
线程池中活跃的线程数: 1
线程池中活跃的线程数: 2
线程池中活跃的线程数: 3
线程池中活跃的线程数: 4
线程池中活跃的线程数: 5
线程池中活跃的线程数: 5
----------------队列中阻塞的线程数1
线程池中活跃的线程数: 5
----------------队列中阻塞的线程数2
线程池中活跃的线程数: 5
----------------队列中阻塞的线程数3
线程池中活跃的线程数: 5
----------------队列中阻塞的线程数4
线程池中活跃的线程数: 5
----------------队列中阻塞的线程数5
线程池中活跃的线程数: 5
----------------队列中阻塞的线程数6
线程池中活跃的线程数: 6
----------------队列中阻塞的线程数6
线程池中活跃的线程数: 7
----------------队列中阻塞的线程数6
线程池中活跃的线程数: 8
----------------队列中阻塞的线程数6
线程池中活跃的线程数: 9
----------------队列中阻塞的线程数6
Exception in thread "main" JAVA.util.concurrent.RejectedExecutionException: Task Thread[Thread15,5,main] rejected from java.util.concurrent.ThreadPoolExecutor@366e2eef[Running, pool size = 9, active threads = 9, queued tasks = 6, completed tasks = 0]
at java.base/java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2055)
at java.base/java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:825)
at java.base/java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1355)
at com.example.test.util.ThreadPoolTest.main(ThreadPoolTest.java:27)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)
刚开始正常创建线程,当数量高于核心线程数5时,将任务添加的工作队列,达到工作队列上限6时 ,新的任务又会创建新的普通线程,直到达到线程池最大的线程数量9个,后面的任务则根据配置的饱和策略来处理
,