java中的线程池

一、ThreadPoolExecutor线程池执行流程流程

            来源引自:https://blog.csdn.net/fuyuwei2015/article/details/72758179

             

            对RejectedExecutionHandler(拒绝策略)接口的解释:在使用线程池并使用有界队列时,如果队列满了,任务添加到线

            程池就会有问题,为此提供了拒绝策略。策略有以下几种:

                    (1)、AbortPolicy:线程池默认的策略,如果任务添加到线程池失败,会抛出RejectedExecutionException异常

                                        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
                                                //不做任何处理,直接抛出异常
                                                throw new RejectedExecutionException("Task " + r.toString() +
                                                         " rejected from " +
                                                         e.toString());

                                            }

                    (2)、DiscardPolicy:如果添加任务失败,则放弃,不会抛出任何异常

                                   public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
                                //就是一个空的方法

                                    }

                    (3)、DiscardOldesPolicy:如果任务添加到线程池失败,会将队列中最早添加的任务移除;并再次尝试添加,如果

                            添加失败则会继续按照该策略执行

                                    public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
                                                if (!e.isShutdown()) {
                                                    //移除队头元素
                                                        e.getQueue().poll();
                                                        //再尝试入队
                                                        e.execute(r);
                                                }

                                    }

                       (4)、CallerRunsPolicy:如果任务添加失败,主线程会自己调用执行器中的execute方法来执行该任务

                                public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
                                            if (!e.isShutdown()) {
                                                    //直接执行run方法
                                                    r.run();
                                             }
                                 }

猜你喜欢

转载自blog.csdn.net/u013226533/article/details/80082696