线程池

1. 为什么要使用线程池:线程复用

2. 三大方法、七大参数、四大策略:

  • 三大方法

     // 单例,只能有一个线程!
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        // 固定的线程数
        ExecutorService threadPool = Executors.newFixedThreadPool(8);
        // 遇强则强!可伸缩!
        ExecutorService threadPool = Executors.newCachedThreadPool();

  • 七大参数

1 public ThreadPoolExecutor(int corePoolSize,     // 核心池线程数大小 (常用) //平时柜台数量
2                 int maximumPoolSize, // 最大的线程数大小 (常用) //最大柜台数
3                 long keepAliveTime,  // 超时等待时间 (常用) //平时不开的柜台在超时到达时会关闭
4                 TimeUnit unit,       // 时间单位 (常用) //侯客区
5                 BlockingQueue<Runnable> workQueue, // 阻塞队列(常用)
6                 ThreadFactory threadFactory,      // 线程工厂
7                 RejectedExecutionHandler handler // 拒绝策略(常用) //侯客区满了 柜台满了时 被拒绝的策略
8 ) 
  • 四大策略

1 /**
2          * 1、ThreadPoolExecutor.AbortPolicy();  抛出异常,丢弃任务4          
3      * 2、ThreadPoolExecutor.DiscardPolicy();不抛出异常,丢弃任务
5 * 3、ThreadPoolExecutor.DiscardOldestPolicy(); 尝试获取任务,不一定执行! 6 * 4、ThreadPoolExecutor.CallerRunsPolicy(); 哪来的去哪里找对应的线程执行! 7 */

 

代码

 1 public class ThreadPoolDemo01 {
 2     public static void main(String[] args) {
 3 //        ExecutorService threadPool = Executors.newSingleThreadExecutor();
 4 //        ExecutorService threadPool = Executors.newFixedThreadPool(8);
 5 //        ExecutorService threadPool = Executors.newCachedThreadPool();
 6         ExecutorService threadPool = new ThreadPoolExecutor(
 7                 2, //平时柜台数量
 8                 5, //最大柜台数
 9                 3L, //平时不开的柜台在超时到达时会关闭
10                 TimeUnit.SECONDS,
11                 new LinkedBlockingDeque<>(3), //侯客区
12                 Executors.defaultThreadFactory(),
13                 //侯客区满了 被拒绝的策略:
14 //                new ThreadPoolExecutor.DiscardPolicy()   //不抛出异常,丢弃任务。 做8次
15 //                new ThreadPoolExecutor.AbortPolicy()     // 抛出异常,丢弃任务。 做8次
16                 new ThreadPoolExecutor.DiscardOldestPolicy() // 尝试获取任务,不一定执行
17 //                new ThreadPoolExecutor.CallerRunsPolicy() //让父线程执行
18         );
19         try {
20             for (int i = 0; i < 9; i++) {
21                 threadPool.execute(() -> {
22                     try {
23                         //模拟阻塞,效率低的情况
24                         TimeUnit.SECONDS.sleep(2L);
25                     } catch (InterruptedException e) {
26                         e.printStackTrace();
27                         e.getMessage();
28                     }
29                     System.out.println(Thread.currentThread().getName() + " ok");
30                 });
31             }
32         } catch (Exception e) {
33             e.printStackTrace();
34         } finally {
35             threadPool.shutdown();
36         }
37     }
38 }
  • 银行办理业务场景:

  • 最大线程池 该如何设置

    • CPU密集型: 根据CPU的处理器数量来定!保证最大效率
    • IO密集型: 50 个线程都是进程操作大io资源, 比较耗时! > 这个常用的 IO 任务数!
posted @ 2020-03-07 16:57  jk2330  阅读(118)  评论(0)    收藏  举报