线程池工作流程-验证

线程池工作流程:

  1、如果正在运行的线程数量小于 corePoolSize,那么马上创建线程运行这个任务

  2、如果正在运行的线程数量大于或等于 corePoolSize,那么将这个任务放入队列

  3、如果这时候队列满了,而且正在运行的线程数量小于 maximumPoolSize,那么还是要创建非核心线程立刻运行这个任务

  4、如果队列满了,而且正在运行的线程数量大于或等于 maximumPoolSize,那么默认拒绝策略下线程池会抛出异常RejectExecutionException

实验:拒绝策略 设置默认的 AbortPolicy,另外三种拒绝策略略

public class ThreadPoolTest1 {

public static void main(String[] args) throws InterruptedException {
Runnable runnable = new Runnable() {
@SneakyThrows
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"--"+System.currentTimeMillis());
Thread.sleep(1000);
}
};

ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 2, 5, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(5), new ThreadPoolExecutor.AbortPolicy());
System.out.println("核心线程数:"+pool.getCorePoolSize());
System.out.println("最大线程数:"+pool.getMaximumPoolSize());
System.out.println("线程池大小:"+pool.getPoolSize());
System.out.println("队列大小:"+pool.getQueue().size());
System.out.println("################################");

for (; ; ) {
pool.submit(runnable);
Thread.sleep(100);
System.out.println("核心线程数:"+pool.getCorePoolSize());
System.out.println("最大线程数:"+pool.getMaximumPoolSize());
System.out.println("线程池大小:"+pool.getPoolSize());
System.out.println("队列大小:"+pool.getQueue().size());
System.out.println("-----------------------------------");
}
}

}


实验结果:

Connected to the target VM, address: '127.0.0.1:5168', transport: 'socket'
核心线程数:1
最大线程数:2
线程池大小:0
队列大小:0
################################
pool-1-thread-1--1595947653191
核心线程数:1
最大线程数:2
线程池大小:1
队列大小:0
-----------------------------------
核心线程数:1
最大线程数:2
线程池大小:1
队列大小:1
-----------------------------------
核心线程数:1
最大线程数:2
线程池大小:1
队列大小:2
-----------------------------------
核心线程数:1
最大线程数:2
线程池大小:1
队列大小:3
-----------------------------------
核心线程数:1
最大线程数:2
线程池大小:1
队列大小:4
-----------------------------------
核心线程数:1
最大线程数:2
线程池大小:1
队列大小:5
-----------------------------------
pool-1-thread-2--1595947653791
核心线程数:1
最大线程数:2
线程池大小:2
队列大小:5
-----------------------------------
Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@38082d64 rejected from java.util.concurrent.ThreadPoolExecutor@5f2050f6[Running, pool size = 2, active threads = 2, queued tasks = 5, completed tasks = 0]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)
at com.heeexy.example.test.multithread.threadPool.ThreadPoolTest1.main(ThreadPoolTest1.java:30)
pool-1-thread-1--1595947654191
pool-1-thread-2--1595947654793
pool-1-thread-1--1595947655191
pool-1-thread-2--1595947655793
pool-1-thread-1--1595947656191

猜你喜欢

转载自www.cnblogs.com/wxseng/p/13394427.html