自定义线程池以及其异常统一处理

2025-07-12  本文已影响0人  flyjar

1、先自定一个一个线程池,指定自定义线程生产工厂CustomThreadFactory

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class ThreadPoolConfig {

    @Bean("customThreadPool")
    public ThreadPoolTaskExecutor customThreadPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(20);
        executor.setThreadNamePrefix("custom-thread-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
         executor.setThreadFactory(new CustomThreadFactory ());
        executor.initialize();
        return executor;
    }
}    

2、声明线程生产工厂,指定自定义的异常处理类CustomUncaughtExceptionHandler

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class CustomThreadFactory implements ThreadFactory {

    private final String namePrefix;
    private final AtomicInteger threadNumber = new AtomicInteger(1);

    public CustomThreadFactory(String namePrefix) {
        this.namePrefix = namePrefix + "-";
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r, namePrefix + threadNumber.getAndIncrement());
        thread.setUncaughtExceptionHandler(new CustomUncaughtExceptionHandler());
        return thread;
    }
}    

3、自定义异常处理类

import java.lang.Thread.UncaughtExceptionHandler;

public class CustomUncaughtExceptionHandler implements UncaughtExceptionHandler {

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.err.println("线程异常捕获: " + t.getName() + " 抛出异常: " + e.getMessage());
        // 这里可以添加统一的异常处理逻辑
        // 例如记录日志、发送告警等
        e.printStackTrace();
    }
}    

4、声明异步service

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {

    @Async("customThreadPool")
    public void executeTask() {
        throw new RuntimeException("测试异步任务异常");
    }
}    

5、在controller中调用service

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Autowired
    private AsyncService asyncService;

    @GetMapping("/test")
    public String test() {
        asyncService.executeTask();
        return "Task submitted";
    }
}    
上一篇 下一篇

猜你喜欢

热点阅读