亲宝软件园·资讯

展开

Java AbortPolicy

​ Gxin   ​ 人气:0

线程池ThreadPoolExecutor的拒绝策略

线程池中的线程资源全部被占用时,对新添加的Task任务有不同的处理策略,在默认的情况下,

ThreadPoolExecutor类中有4种不同的处理方式:

AbortPolicy策略

AbortPolicy策略是当任务添加到线程池中被拒绝时,它将抛出RejectedExecutionException异常。

线程执行代码如下:

public class FirstRunnable implements Runnable {
    @Override
    public void run() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
        try {
            System.out.println(Thread.currentThread().getName() +"  开始时间:"+simpleDateFormat.format(new Date()));
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() +"  结束时间:"+simpleDateFormat.format(new Date()));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

运行类代码如下:

public class AbortPolicyRun {
    public static void main(String[] args) {
        FirstRunnable firstRunnable = new FirstRunnable();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 3, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2), new ThreadPoolExecutor.AbortPolicy());
        for (int i = 0; i < 7 ; i++) {
            threadPoolExecutor.execute(firstRunnable);
        }
    }
}

运行结果如下:

Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task com.ozx.concurrentprogram.executor.service.FirstRunnable@6c629d6e rejected from java.util.concurrent.ThreadPoolExecutor@5f5a92bb[Running, pool size = 3, active threads = 3, queued tasks = 2, completed tasks = 0]
    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.ozx.concurrentprogram.executor.controller.AbortPolicyRun.main(AbortPolicyRun.java:19)
pool-1-thread-3  开始时间:16:20:27
pool-1-thread-1  开始时间:16:20:27
pool-1-thread-2  开始时间:16:20:27
pool-1-thread-2  结束时间:16:20:28
pool-1-thread-2  开始时间:16:20:28
pool-1-thread-1  结束时间:16:20:28
pool-1-thread-1  开始时间:16:20:28
pool-1-thread-3  结束时间:16:20:28
pool-1-thread-1  结束时间:16:20:29
pool-1-thread-2  结束时间:16:20:29

使用AbortPolicy策略后,线程任务数量超出线程池最大线程数时,线程池将抛出java.util.concurrent.RejectedExecutionException异常。

加载全部内容

相关教程
猜你喜欢
用户评论