线程池:7大参数

2023-12-27 09:21:52

/**

* 7大参数

*

* 特别注意:线程池不允许使用Executors创建、而是通过ThreadPoolExecutor的方式

* 因为FixedThreadPool和SingleThreadExecutor允许请求的的队列长度是Integer.MAX_VALUE、会堆积大量请求、导致OOM

* 因为CachedThreadPool和ScheduledThreadPool允许创建线程数量是Integer.MAX_VALUE、会创建大量线程、导致OOM

*

* ?源码分析1

* ?????????public static ExecutorService newSingleThreadExecutor() {

* ????????????return new Executors.FinalizableDelegatedExecutorService

* ????????????????????(new ThreadPoolExecutor(1, 1,

* ????????????????????????????0L, TimeUnit.MILLISECONDS,

* ????????????????????????????new LinkedBlockingQueue<Runnable>()));

* ????????}

*

* ?源码分析2

* ???????public static ExecutorService newFixedThreadPool(int nThreads) {

* ????????????return new ThreadPoolExecutor(nThreads, nThreads,

* ????????????????????0L, TimeUnit.MILLISECONDS,

* ????????????????????new LinkedBlockingQueue<Runnable>());

* ????????}

*

* ?源码分析3

* ????????public static ExecutorService newCachedThreadPool() {

* ????????????return new ThreadPoolExecutor(0, Integer.MAX_VALUE,

* ????????????????????60L, TimeUnit.SECONDS,

* ????????????????????new SynchronousQueue<Runnable>());

* ????????}

*

*

*

*/

public class Thread10 {

// ?重点:本质:ThreadPoolExecutor7大参数

//public ThreadPoolExecutor(int corePoolSize, ????核心线程池大小

// ?????????????????????????int maximumPoolSize, ?最大核心线程池大小

// ?????????????????????????long keepAliveTime, ??超时了没有人调用就会释放

// ?????????????????????????TimeUnit unit, ???????超时单位

// ?????????????????????????BlockingQueue<Runnable> workQueue, ??阻塞队列

// ?????????????????????????ThreadFactory threadFactory, ????????线程工厂

// ?????????????????????????RejectedExecutionHandler handler) ???拒绝策略

// 重点:本质:4种拒绝策略

// ThreadPoolExecutor.AbortPolicy 银行满了、还有人进来、不处理这个人的、抛出异常

// ThreadPoolExecutor.CallerRunsPolicy 哪来的去哪里

// ThreadPoolExecutor.DiscardPolicy 队列满了、丢掉任务、不会抛出异常

// ThreadPoolExecutor.DiscardOldestPolicy} 队列满了、尝试去和最早的竞争、不会抛出异常

// 读源码的好处、掌握原理、更深入透彻的使用、例如HashMap

// ???????Map map = new HashMap();// 16、0.75

// ???????Map map2 = new HashMap<>(10, 0.5F);

}

文章来源:https://blog.csdn.net/u010605984/article/details/135212891
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。