【并发编程】- 线程池使用AbortPolicy策略

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第31天,点击查看活动详情

线程池ThreadPoolExecutor的拒绝策略

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

  • AbortPolicy:当任务添加到线程池中被拒绝时,它将抛出RejectExecutionException异常。
  • CallerRunsPolicy:当任务添加到线程池中被拒绝时,会使用调用线程池的Thread线程对象处理被拒绝的任务。
  • DiscardOldestPolicy: 当任务添加到线程池中被拒绝时,线程池会放弃等待队列中最旧的未处理任务,然后将被拒绝的任务添加到等待队列中。
  • DiscardPolicy:当任务添加到线程池中被拒绝时,线程池将丢弃被拒绝的任务。

1.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异常。

猜你喜欢

转载自juejin.im/post/7114575627835047950