java线程池的拒绝策略
Java中的线程池拒绝策略定义了当任务无法执行时如何处理这些任务。以下是Java中常见的拒绝策略:
一、CallerRunsPolicy
#:当任务被拒绝添加时,如果调用者所在的线程不是线程池中的线程,那么任务将由该调用者所在的线程直接执行。
ExecutorService executor = new ThreadPoolExecutor(
corePoolSize, maximumPoolSize, keepAliveTime,
TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(queueSize),
new ThreadPoolExecutor.CallerRunsPolicy());
二、AbortPolicy
#:这是默认的拒绝策略,不执行新任务并抛出RejectedExecutionException异常。
ExecutorService executor = new ThreadPoolExecutor(
corePoolSize, maximumPoolSize, keepAliveTime,
TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(queueSize),
new ThreadPoolExecutor.AbortPolicy());
三、DiscardPolicy
#:不执行新任务,但是不抛出异常。
ExecutorService executor = new ThreadPoolExecutor(
corePoolSize, maximumPoolSize, keepAliveTime,
TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(queueSize),
new ThreadPoolExecutor.DiscardPolicy());
四、DiscardOldestPolicy
#:不执行新任务,而是抛弃队列中最老的未处理任务,然后尝试再次执行新任务。
ExecutorService executor = new ThreadPoolExecutor(
corePoolSize, maximumPoolSize, keepAliveTime,
TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(queueSize),
new ThreadPoolExecutor.DiscardOldestPolicy());
总结
在创建ThreadPoolExecutor时,可以选择一种拒绝策略,并将其传递给构造函数。例如,使用CallerRunsPolicy可以保证任务最终会被执行,但这可能会影响客户端的响应性。其他策略则在任务拒绝时不提供任何保证。根据应用程序的需求选择合适的拒绝策略。
标签:Java,拒绝,keepAliveTime,任务,线程,new,ThreadPoolExecutor From: https://blog.csdn.net/MircoO/article/details/139476021