ExecutorService 实现子线程执行完后执行 CountDownLatch 实现

线程类:


import lombok.Data;
import java.util.List;
import java.util.concurrent.CountDownLatch;

@Data
public class Excuteor implements Runnable {

    private List<Integer> list =null;


    private CountDownLatch countDownLatch;

    @Override
    public void run() {
        try {
            if(list!=null && list.size()>0){
                list.forEach(integer -> System.out.println(integer));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //让现有线程计数器-1
            countDownLatch.countDown();
        }

    }
}

测试类


import com.unicom.initperson.entity.Excuteor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

@Slf4j
@RestController
@RequestMapping("test")
public class testController {



    //单线程执行数量设设定为2000
    final  static  Integer singleCount=4000;

    @Autowired
    private ExecutorService executorService;


    @GetMapping
    public void threadTest() {
        this.execute(this.getTestData());
    }


    public void execute(List<Integer> list){
        Integer count=list.size();
        Integer threadCount= count/singleCount;
        if(count%singleCount!=0)threadCount++;
        if(threadCount>30) return;
        CountDownLatch countDownLatch= new CountDownLatch(threadCount);
        for (int i = 0; i <threadCount ; i++) {
           Excuteor excuteor = new Excuteor();
            excuteor.setList(i!=threadCount-1? list.subList( i*singleCount,(i+1)*singleCount):list.subList( i*singleCount,list.size()-1));
            excuteor.setCountDownLatch(countDownLatch);
            executorService.execute(excuteor);
        }
        try {
            countDownLatch.await();
            log.info("开启的线程数:"+threadCount);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    private static List<Integer> getTestData() {
        List<Integer> list =new ArrayList<>();
        for (int i = 0; i < 12001; i++) {
            list.add(i + 1);
        }
        return list;
    }


}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值