组成:
核心池
队列
主要参数:
核心池大小;
最大线程数;
队列大小;
活动保持时间;(无任务执行是任务多久关闭)
创建:
(1) new ThreadPoolExecutor();
(2)Executors的静态方法
单个线程的线程池
缓存的线程池
固定大小的线程池
定时线程池
Executors的静态方法底层依旧是调用ThreadPoolExecutor()
添加线程:
(1) exeute()
无返回值,无法得知添加的状况
(2)submit()
会返回一个Future对象,可以用来获得线程的各种状态
向线程池中添加线程:
核心池是否已满?-->>否:在线程池离创建线程/是:->>队列是否已满?否:在队列中创建线程/是:->>是否达到线程池最大数目?否:在线程池中添加线程/是:拒绝策略
拒绝策略:
AboutPolicy 不添加,返回异常
DiscardPolicy 不添加,返回异常
DiscardPolicy 将当前的第一个任务替换成当前新任务
CallerRunPolicy 拒绝新任务
关闭:
shutdown()
shutdownNow()
[1]: https://juejin.im/post/5b3cf259e51d45194e0b7204
源码分析
The runState provides the main lifecycle control, taking on values:
*
* RUNNING: Accept new tasks and process queued tasks
* SHUTDOWN: Don't accept new tasks, but process queued tasks
* STOP: Don't accept new tasks, don't process queued tasks,
* and interrupt in-progress tasks
* TIDYING: All tasks have terminated, workerCount is zero, 过度状态
* the thread transitioning to state TIDYING
* will run the terminated() hook method
* TERMINATED: terminated() has completed
https://mp.weixin.qq.com/s/6Wil_y3wAFjtA0wjaZNLBQ
网友评论