美文网首页
ThreadPoolExecutor饱和策略

ThreadPoolExecutor饱和策略

作者: Android刘东 | 来源:发表于2020-09-01 16:13 被阅读0次

    ThreadPoolExecutor线程池默认的饱和策略是 AbortPolicy

    private static final RejectedExecutionHandler defaultHandler =
            new AbortPolicy();
    

    1)CallerRunsPolicy 自己去执行该任务直接run,不会等待线程池中的线程去执行.

        public static class CallerRunsPolicy implements RejectedExecutionHandler {
            public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
                if (!e.isShutdown()) {
                    r.run();
                }
            }
        }
    
    

    2)AbortPolicy 抛出异常RejectedExecutionException

        public static class AbortPolicy implements RejectedExecutionHandler {
            public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
                throw new RejectedExecutionException("Task " + r.toString() +
                                                     " rejected from " +
                                                     e.toString());
            }
        }
    
    

    3)DiscardPolicy 放弃

    public static class DiscardPolicy implements RejectedExecutionHandler {
         
            public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            }
        }
    

    4)DiscardOldestPolicy去除第一个 也就是最老的队列

        public static class DiscardOldestPolicy implements RejectedExecutionHandler {
            public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
                if (!e.isShutdown()) {
                    e.getQueue().poll(); //进入Deque<E> 类中的 E poll()方法;
                    /*如  public E poll() {
            return pollFirst();
            }
      */ 
                    e.execute(r);
                }
            }
        }
    
    

    5)也可以自定义 实现RejectedExecutionHandler

    相关文章

      网友评论

          本文标题:ThreadPoolExecutor饱和策略

          本文链接:https://www.haomeiwen.com/subject/gumvsktx.html