线程池--默认拒绝策略

本文适合java初学者。

当任务提交后,被拒绝策略有多种,例如CallerRunsPolicy,AbortPolicy,DiscardPolicy,DiscardOldestPolicy等等

本文我们看下,默认策略的使用方式。(一般是捕获异常)

默认拒绝策略JDK8.0:

    /**

    * The default rejected execution handler

    */

    private static final RejectedExecutionHandler defaultHandler =

        new AbortPolicy();

示例

public static void main(String[] args) {

    ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1,

            0L, TimeUnit.MILLISECONDS,

            new LinkedBlockingQueue(1));

    for(int i = 0;i<10;i++){

        final int finalI = i;

        try {

            executor.submit(new Runnable() {

                @Override

                public void run() {

                    System.out.println(String.format("处理第%s个任务", finalI));

                }

            });

        }catch (Exception e){

            System.out.println(finalI+"异常了"+ Jackson.toJson(executor));

        }

    }

}

结果:

处理第0个任务

处理第1个任务

2异常了{"largestPoolSize":1,"completedTaskCount":2,"threadFactory":{},"corePoolSize":1,"maximumPoolSize":1,"activeCount":0,"poolSize":1,"queue":[],"rejectedExecutionHandler":{},"taskCount":2,"shutdown":false,"terminated":false,"terminating":false}

4异常了{"largestPoolSize":1,"completedTaskCount":2,"threadFactory":{},"corePoolSize":1,"maximumPoolSize":1,"activeCount":0,"poolSize":1,"queue":[{"done":false,"cancelled":false}],"rejectedExecutionHandler":{},"taskCount":3,"shutdown":false,"terminated":false,"terminating":false}

5异常了{"largestPoolSize":1,"completedTaskCount":2,"threadFactory":{},"corePoolSize":1,"maximumPoolSize":1,"activeCount":0,"poolSize":1,"queue":[{"done":false,"cancelled":false}],"rejectedExecutionHandler":{},"taskCount":3,"shutdown":false,"terminated":false,"terminating":false}

6异常了{"largestPoolSize":1,"completedTaskCount":2,"threadFactory":{},"corePoolSize":1,"maximumPoolSize":1,"activeCount":0,"poolSize":1,"queue":[{"done":false,"cancelled":false}],"rejectedExecutionHandler":{},"taskCount":3,"shutdown":false,"terminated":false,"terminating":false}

7异常了{"largestPoolSize":1,"completedTaskCount":2,"threadFactory":{},"corePoolSize":1,"maximumPoolSize":1,"activeCount":0,"poolSize":1,"queue":[{"done":false,"cancelled":false}],"rejectedExecutionHandler":{},"taskCount":3,"shutdown":false,"terminated":false,"terminating":false}

8异常了{"largestPoolSize":1,"completedTaskCount":2,"threadFactory":{},"corePoolSize":1,"maximumPoolSize":1,"activeCount":0,"poolSize":1,"queue":[{"done":false,"cancelled":false}],"rejectedExecutionHandler":{},"taskCount":3,"shutdown":false,"terminated":false,"terminating":false}

9异常了{"largestPoolSize":1,"completedTaskCount":2,"threadFactory":{},"corePoolSize":1,"maximumPoolSize":1,"activeCount":0,"poolSize":1,"queue":[{"done":false,"cancelled":false}],"rejectedExecutionHandler":{},"taskCount":3,"shutdown":false,"terminated":false,"terminating":false}

处理第3个任务

你可能感兴趣的:(线程池--默认拒绝策略)