处理批量业务数据,多线程的使用

1、查询数据列表

2、自定义线程池配置,类注解@Configuration

	/**
	 * 自定义线程池
	 */
	@Bean(name = "executor")
	public ExecutorService executorService(){
		return new ThreadPoolExecutor(
				5, // 核心线程数
				10, // 最大线程数
				60L, // 线程存活时间
				TimeUnit.SECONDS, // 时间单位
				new ArrayBlockingQueue<>(100), // 任务队列
				new ThreadPoolExecutor.CallerRunsPolicy());
	}

3、注入使用,获取bean

#例如
@Autowired
private ExecutorService executor;

4、定义执行线程thread类,注意有些内容线程不安全,需要在外面定义好传进来,以保证线程安全,同样线程里最好不要调用接口之类的,需要接口使用SpringBeanUtils.getBean(name)获取。


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.concurrent.CountDownLatch;

/**
 * xx业务多线程处理
 */
public class XXThread implements Runnable{
    Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    private final CountDownLatch latch;
    private final 传入业务参数或者对象 c;


    public XXThread (参数或者对象  c, CountDownLatch countDownLatch) {
        this.c= c;
        this.latch = countDownLatch;
    }

    @Override
    public void run() {
        logger.info("当前执行线程:"+Thread.currentThread().getName());
        try {
            logger.info("是否进来了");
            //业务
            ...........
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            latch.countDown();
        }
    }
}

5、循环列表单独执行每个线程,之前前传入计数器

CountDownLatch latch = new CountDownLatch(list.size());

for(Object o:list){
    ClassThread thread = new ClassThread(o,latch)
    executor.execute(thread);
}

try {
			latch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		executor.shutdown();
		while (!executor.isTerminated()){

		}
		if (executor.isTerminated()){
			logger.info("线程执行完成");
		}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞流银河

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值