温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java线程池怎么使用AbortPolicy策略

发布时间:2022-06-30 09:57:59 来源:亿速云 阅读:414 作者:iii 栏目:开发技术

本篇内容介绍了“Java线程池怎么使用AbortPolicy策略”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

线程池ThreadPoolExecutor的拒绝策略

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

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

  • AbortPolicy:当任务添加到线程池中被拒绝时,它将抛出RejectExecutionException异常。

  • CallerRunsPolicy:当任务添加到线程池中被拒绝时,会使用调用线程池的Thread线程对象处理被拒绝的任务。

  • DiscardOldestPolicy: 当任务添加到线程池中被拒绝时,线程池会放弃等待队列中最旧的未处理任务,然后将被拒绝的任务添加到等待队列中。

  • DiscardPolicy:当任务添加到线程池中被拒绝时,线程池将丢弃被拒绝的任务。

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

“Java线程池怎么使用AbortPolicy策略”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI