线程池

名字:Executor 

我的需求:一个list,对list数查库,逻辑处理,返回统计结果。

为啥用多线程:逻辑处理太多,一个回合太慢。

使用:创建Executor对象;业务类抽出来,分装成类,实现Callable;主线程中excturor对象提交list;用countdown来控制主线程等待子线程执行完返回结果再执行;从future取出结果继续执行主线程其他业务。


 

代码:主线程

public class MainThread {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //线程计数器
        final CountDownLatch count = new CountDownLatch(10);
        //线程执行类
//        ExecutorService executor= Executors.newFixedThreadPool(10);
        ExecutorService executor= Executors.newCachedThreadPool();

        //线程返回结果接收
        List<Future<List<String>>>  resutlList=new ArrayList<>();
        //待线程处理list
        List<Integer> sourceList=new ArrayList<>();
        for (int i=0;i<1000;i++){
            sourceList.add(i);
        }
        //创建业务类对象
        Factory factory=new Factory(sourceList,count);
        //业务对象提交给线程池
        for (int i=0;i<10;i++) {
            Future<List<String>> result = executor.submit(factory);
            resutlList.add(result);
        }
        count.await();
        System.out.println("子线程执行完");
        System.out.println(resutlList.size());
        for (int i=0;i<resutlList.size();i++){
            Future<List<String>> result1=resutlList.get(i);
            List<String> resultTotal=result1.get();
            for (int j=0;j<resultTotal.size();j++){
//                System.out.println(resultTotal.get(j));
            }
        }
    }
}

抽象出的业务类:

public class Factory implements Callable<List<String>> {

    public List<Integer> integerList;
    public CountDownLatch countDown;

    public Factory(List<Integer> integerList, CountDownLatch countDown) {
        this.integerList = integerList;
        this.countDown = countDown;
    }

    @Override
    public List<String> call() throws Exception {
        String descb=null;
        List<String>  resutlList=new ArrayList<>();
        for (int i = 0; i < integerList.size(); i++){
             descb = Thread.currentThread().getName() + "执行第:" + i + "个list";
             System.out.println(descb);
             resutlList.add(descb);
        }
        countDown.countDown();
        return resutlList;
    }
}

遇到问题:业务代码可能参数很多,入参和出参都有一堆,转化很多。一个list进去,需要将结果类都初始化一遍,最后在给每个结果赋值。返回主线程,在future处还要转化好几层,建立若干个对象。如果是统计结果,还需要将结果合起来。不过耗时长的任务还是很值得的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值