线程池

线程池

参考博客:

Spring 中的几种线程池使用总结java spring 线程池程序猿 java 易的博客-CSDN 博客

Spring 环境中正确关闭线程池的姿势spring 优雅关闭线程池神的力量的博客-CSDN 博客

多线程系列:二、线程池在 Spring 中的使用与关闭_BigBug_500 的博客-CSDN 博客

实践:

/**
 * @author xiashuo
 * @date 2023/6/12 15:46
 */
@Configuration
@EnableAsync
public class NodeCheckConfig implements ApplicationListener<ContextClosedEvent> {

    protected static Log log = LogFactory.getLog(NodeCheckConfig.class);

    private ListeningExecutorService service;

    //  线程工厂名称
    private static final ThreadFactory FACTORY = new BasicThreadFactory.Builder().namingPattern("node-check-pool-").daemon(false).build();

    @Bean("nodeCheckExecutor")
    public ListeningExecutorService asyncServiceExecutor() {
        log.info("start node-check thread executor ");

        ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 20, 120, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(200),
                new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setThreadFactory(FACTORY);

        ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(executor);
        service = listeningExecutorService;

        return listeningExecutorService;
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
        if (service != null) {
            service.shutdown();
            try {
                service.awaitTermination(5, TimeUnit.SECONDS);
                log.info("node-check thread executor stop success ");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

使用

@Autowired
@Qualifier("nodeCheckExecutor")
private ListeningExecutorService nodeCheckExecutor;


try {
    ListenableFuture<Integer> submit = nodeCheckExecutor.submit(() -> threadService.bbs(990));
    //异步监听任务是否执行成功,如果不需要监听,可以不写
    Futures.addCallback(submit, new FutureCallback<Integer>() {
        @Override
        public void onSuccess(@Nullable Integer integer) {
            log.info("装饰线程执行成功了");
        }

        @Override
        public void onFailure(Throwable throwable) {
            System.out.println("执行失败了,重新调用");
            //threadService.bbs(990);
        }
    },listeningExecutorService);
    Integer integer = submit.get();
    log.info("获得最终结果为:"+integer);
}catch (Exception e){
    e.printStackTrace();
}