线程池使用

本文详细介绍了三种在Spring框架中使用ThreadPool的方式,包括通过@Configuration注解配置ThreadPoolTaskExecutor,静态工厂方法创建ExecutorService,以及不推荐的每次都new的方式。重点展示了如何设置线程池参数和执行任务。
摘要由CSDN通过智能技术生成

方式一(@Configuration):

package com.vanlinks.utils;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@EnableAsync
@Configuration
public class ThreadPoolConfig {

    /**
     * 核心线程数
     */
    private static final int CORE_POOL_SIZE = 4;

    /**
     * 最大线程数
     */
    private static final int MAX_POOL_SIZE = 20;

    /**
     * 等待队列
     */
    private static final int QUEUE_CAPACITY = 100;

    @Bean("authExecutor")
    public Executor authExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CORE_POOL_SIZE);
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        // 设置队列容量
        executor.setQueueCapacity(QUEUE_CAPACITY);
        // 设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("vanlinks-pool#Task");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;

    }
}
使用:
private final Executor authExecutor;
    @Open
    @GetMapping("/hello")
    public String test() {
        System.out.println("authExecutor:" + authExecutor);
        }

方式二(static):

package com.vanlinks.utils;

import javax.annotation.PreDestroy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class CustomThread {

 public static ExecutorService riskThreadPool =
         new ThreadPoolExecutor(5, 10, 2, TimeUnit.SECONDS, new LinkedBlockingQueue<>());

 /**
  * 关闭线程池
  */
 @PreDestroy
 public static void closeThreadPool(ExecutorService executorService, boolean shutdownNow) {
     if (shutdownNow)
         executorService.shutdownNow();
     else
         executorService.shutdown();
 }

 public static void closeThreadPool(ExecutorService executorService) {
     closeThreadPool(executorService, false);
 }

}

使用:
private void getBlackListAndLoanBalanceInfo(String filterParam, List<NodeDataDTO> nodeDataDTOList) {
        ExecutorService pool = CustomThread.riskThreadPool;
        final CountDownLatch latch = new CountDownLatch(nodeDataDTOList.size());
        for (NodeDataDTO nodeDataDTO : nodeDataDTOList) {
            Runnable run = () -> {
                Integer blackListInfo = enterpriseMapper.getBlackListInfo(nodeDataDTO.getName());
                Integer loanBalInfo = enterpriseMapper.getLoanBalanceInfo(nodeDataDTO.getName());
                if (blackListInfo > 0 && loanBalInfo > 0) {
                    nodeDataDTO.setInfo("2");
                    System.out.println(nodeDataDTO.getName() + "------------------------------------" + nodeDataDTO.getInfo());
                } else if (blackListInfo > 0 && loanBalInfo == 0) {
                    nodeDataDTO.setInfo("0");
                    System.out.println(nodeDataDTO.getName() + "------------------------------------" + nodeDataDTO.getInfo());
                } else if (blackListInfo == 0 && loanBalInfo > 0) {
                    nodeDataDTO.setInfo("1");
                    System.out.println(nodeDataDTO.getName() + "------------------------------------" + nodeDataDTO.getInfo());
                }
                //}
                latch.countDown();
            };
            pool.execute(run);
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

方式三(每次new(),不推荐):


        ExecutorService riskThreadPool =
                new ThreadPoolExecutor(5, 10, 2, TimeUnit.SECONDS, new LinkedBlockingQueue<>());

        System.out.println("riskThreadPool:" + riskThreadPool);
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值