线程池底层工作原理

1.说说线程池的底层工作原理?

 public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.acc = System.getSecurityManager() == null ?
                null :
                AccessController.getContext();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

2.线程池的主要流程 

解析:使用者就是来银行办理业务的老头老太太们,首先核心数就是corePoolSize,没有满,两个窗口就来了一个顾客,满了之后去候客区等着去阻塞队列,如果候客区椅子很多,阻塞对列没有满,就等着,等着,但是抱歉,候客区(阻塞对列也满了)也满了,马工和行长反应情况,多来几个人加个班,这个时候就是我们刚才所说的从2个线程扩展到5个线程,线程池是否达到最大数,没有满继续干活,满了执行拒绝策略就这四步

 

3.线程池的4中拒绝策略 

 3.1 是什么? 

等待队列已经满了,再也塞不进去新任务,同时线程中的max线程数已经达到了,无法继续提供服务这时候我们就需要拒绝策略机制来处理这个问题

 

3.2 第一种 ThreadPoolExecutor.AbortPolicy()

 默认直接抛出 rejectedExecution 异常阻止系统正常运行


        ExecutorService executorService = new ThreadPoolExecutor(2,5,1L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());

        //10个用户来创办业务,每一个用户就是来自外部的请求线程
         try {
             for (int i = 1; i <=9 ; i++) {
                 executorService.execute(()->{
                     System.out.println(Thread.currentThread().getName()+"\t 办理业务");
                 });
//                  try {
//                        TimeUnit.MILLISECONDS.sleep(200);
//                       } catch (Exception e) {
//                        e.printStackTrace();
//                    }
             }
              } catch (Exception e) {
               e.printStackTrace();
           }finally {
             executorService.shutdown();
         }

输出结果:

输出结果:

pool-1-thread-1     办理业务
pool-1-thread-3     办理业务
pool-1-thread-4     办理业务
pool-1-thread-4     办理业务
pool-1-thread-1     办理业务
pool-1-thread-2     办理业务
pool-1-thread-5     办理业务
pool-1-thread-3     办理业务
java.util.concurrent.RejectedExecutionException: Task com.thread.MyThreadPoolDemo$$Lambda$1/521645586@37bba400 rejected from java.util.concurrent.ThreadPoolExecutor@179d3b25[Running, pool size = 5, active threads = 1, queued tasks = 0, completed tasks = 7]
    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 com.thread.MyThreadPoolDemo.main(MyThreadPoolDemo.java:74)

3.3 第二种 ThreadPoolExecutor.CallerRunsPolicy()

“调用者运行” 一种调节机制该策略既不会抛弃任务也不会拒绝任务,而是将任务回退到调用者。

 ExecutorService executorService = new ThreadPoolExecutor(2,5,1L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),Executors.defaultThreadFactory(),new ThreadPoolExecutor.CallerRunsPolicy());

        //10个用户来创办业务,每一个用户就是来自外部的请求线程
         try {
             for (int i = 1; i <=10 ; i++) {
                 executorService.execute(()->{
                     System.out.println(Thread.currentThread().getName()+"\t 办理业务");
                 });
//                  try {
//                        TimeUnit.MILLISECONDS.sleep(200);
//                       } catch (Exception e) {
//                        e.printStackTrace();
//                    }
             }
              } catch (Exception e) {
               e.printStackTrace();
           }finally {
             executorService.shutdown();
         }

输出结果:

pool-1-thread-1	 办理业务
main	 办理业务
pool-1-thread-3	 办理业务
pool-1-thread-2	 办理业务
pool-1-thread-5	 办理业务
pool-1-thread-3	 办理业务
pool-1-thread-1	 办理业务
pool-1-thread-4	 办理业务
pool-1-thread-5	 办理业务
pool-1-thread-2	 办理业务

 

3.4 第三种 ThreadPoolExecutor.DiscardOldestPolicy()

DiscardOldestPolicy()抛弃队列中等待最久的任务,然后把当前任务加入队列中,尝试再次提交当前任务。


        ExecutorService executorService = new ThreadPoolExecutor(2,5,1L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),Executors.defaultThreadFactory(),new ThreadPoolExecutor.DiscardOldestPolicy());

        //10个用户来创办业务,每一个用户就是来自外部的请求线程
         try {
             for (int i = 1; i <=10 ; i++) {
                 executorService.execute(()->{
                     System.out.println(Thread.currentThread().getName()+"\t 办理业务");
                 });
//                  try {
//                        TimeUnit.MILLISECONDS.sleep(200);
//                       } catch (Exception e) {
//                        e.printStackTrace();
//                    }
             }
              } catch (Exception e) {
               e.printStackTrace();
           }finally {
             executorService.shutdown();
         }

输出结果:

pool-1-thread-1	 办理业务
pool-1-thread-3	 办理业务
pool-1-thread-3	 办理业务
pool-1-thread-2	 办理业务
pool-1-thread-5	 办理业务
pool-1-thread-3	 办理业务
pool-1-thread-4	 办理业务
pool-1-thread-1	 办理业务


 3.4 第四种 ThreadPoolExecutor.DiscardPolicy()

直接丢弃任务不予以任何处理 也不抛出异常,如果允许丢任务这是最好的一种方案

  ExecutorService executorService = new ThreadPoolExecutor(2,5,1L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),Executors.defaultThreadFactory(),new ThreadPoolExecutor.DiscardPolicy());

        //10个用户来创办业务,每一个用户就是来自外部的请求线程
         try {
             for (int i = 1; i <=10 ; i++) {
                 executorService.execute(()->{
                     System.out.println(Thread.currentThread().getName()+"\t 办理业务");
                 });
//                  try {
//                        TimeUnit.MILLISECONDS.sleep(200);
//                       } catch (Exception e) {
//                        e.printStackTrace();
//                    }
             }
              } catch (Exception e) {
               e.printStackTrace();
           }finally {
             executorService.shutdown();
         }

输出结果:

pool-1-thread-2	 办理业务
pool-1-thread-3	 办理业务
pool-1-thread-1	 办理业务
pool-1-thread-5	 办理业务
pool-1-thread-2	 办理业务
pool-1-thread-4	 办理业务
pool-1-thread-1	 办理业务
pool-1-thread-3	 办理业务

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值