Java中线程池有哪些拒绝策略呢?

戚薇 Java经验 发布时间:2023-05-18 22:30:46 阅读数:15044 1
下文笔者讲述java线程池的拒绝策略简介说明,如下所示

线程池的拒绝策略简介

线程池有以下默认策略,也可以自定义拒绝策略:

默认策略:
ThreadPoolExecutor.AbortPolicy:
   丢弃任务并抛出RejectedExecutionException异常。
ThreadPoolExecutor.DiscardPolicy:
   丢弃任务,但是不抛出异常。
ThreadPoolExecutor.DiscardOldestPolicy:
   丢弃队列最前面的任务,然后重新尝试执行任务(重复此过程)
ThreadPoolExecutor.CallerRunsPolicy:
    由调用线程处理该任务(也就是自己处理,不开启新线程)

通过重写RejectedExecutionHandler
    实现自定义一种拒绝或降级策略 
例:线程池拒绝策略的示例
package com.java265.thread;
 
import com.alibaba.fastjson.JSON;
import com.java265.reflect.Student;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 
import javax.annotation.PostConstruct;
import java.lang.reflect.Field;
import java.util.concurrent.*;
 
@Slf4j
public class ThreadPoolTest {
 
    private ThreadPoolTaskExecutor asyncTaskExecutor;
 
    @PostConstruct
    private void init() {
        asyncTaskExecutor = new ThreadPoolTaskExecutor();
        ThreadFactory factory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat("threadName" + "%d").build();
        asyncTaskExecutor.setThreadFactory(factory);
        asyncTaskExecutor.setCorePoolSize(1);
        asyncTaskExecutor.setMaxPoolSize(1);
        asyncTaskExecutor.setAllowCoreThreadTimeOut(true);
        asyncTaskExecutor.setQueueCapacity(10);
        asyncTaskExecutor.setKeepAliveSeconds(3);
        asyncTaskExecutor.setDaemon(true);
        asyncTaskExecutor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                log.error("转MQ处理");
                executorFailSendMQ(r);
            }
        });
        asyncTaskExecutor.initialize();
    }
 
    private void executorFailSendMQ(Runnable r){
        FutureTask task = (FutureTask) r;
        Student student = null;
        //从线程池失败中获取student对象
        try {
            Field callableField = task.getClass().getDeclaredField("callable");
            callableField.setAccessible(true);
            Callable callable = (Callable) callableField.get(task);
            
            Field taskField = callable.getClass().getDeclaredField("task");
            taskField.setAccessible(true);
            AsyncSaveTask asyncSaveTask = (AsyncSaveTask) taskField.get(callable);
            
            student = asyncSaveTask.getStudent();
        }catch (Exception e){
            log.error("executorFailSendMQ error",e);
        }
        if(student != null){
            log.info("executorFailSendMQ send ={}",JSON.toJSONString(student));
            //重新发送mq
        }else{
            log.error("executorFailSendMQ null");
        }
    }
 
    class AsyncSaveTask implements Runnable {
 
        private Student student;
        
        public AsyncSaveTask(Student student) {
            this.student = student;
        }
 
        public Student getStudent() {
            return student;
        }
 
        public void setStudent(Student student) {
            this.student = student;
        }
 
        @Override
        public void run() {
            System.out.println("AsyncSaveTask thread ={}" + Thread.currentThread().getName());
        }
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202305/16844202886526.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者