Callable简单运用

if(CollectionUtil.isNotEmpty(list)){
    Map<String,String> detailTypeMap =
            serviceLocator.getDetailsTypeService().getKeyMap();
    //每个线程处理条数
    int threadSize = 200;
    List<List<DetailView>> partition = Lists.partition(list, threadSize);
    int size = partition.size();
    CountDownLatch begin = new CountDownLatch(size);
    int corePoolSize = 10;
    int maximumPoolSize = 20;
    ThreadPoolExecutor pool = new ThreadPoolExecutor(corePoolSize,
            maximumPoolSize,
            10,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(100));
    try {
        List<Future<List<RecordView>>> futureList = new ArrayList<>();
        for (List<DetailView> tempList : partition) {
            Future<List<RecordView>> future =
                    pool.submit(new Callable1024(serviceLocator,tempList,detailTypeMap));
            futureList.add(future);
            begin.countDown();
        }
        begin.await();
        for (Future<List<RecordView>> listFuture : futureList) {
            List<RecordView> recordViewList = listFuture.get();
            resultList.addAll(recordViewList);
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
        log.error("1024 InterruptedException ", e);
    } catch (RuntimeException e) {
        e.printStackTrace();
        log.error("1024 RuntimeException ", e);
    } catch (ExecutionException e) {
        e.printStackTrace();
        log.error("1024 ExecutionException ", e);
    } finally {
        pool.shutdown();
    }
    log.info("list:" + list.size() + ",resultList:" + resultList.size());
}

ThreadPoolExecutor参数说明:https://www.cnblogs.com/yifanSJ/p/16326293.html;

package com.util;

import com.entity.remote.DetailView;
import com.entity.remote.RecordView;
import com.service.ServiceLocator;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

public class Callable1024 implements Callable<List<RecordView>> {

    private ServiceLocator serviceLocator;

    private List<DetailView> list;

    private Map<String,String> detailTypeMap;

    public Callable1024(ServiceLocator serviceLocator,
                        List<DetailView> list,
                        Map<String,String> detailTypeMap){
        super();
        this.ServiceLocator = serviceLocator;
        this.list = list;
        this.detailTypeMap = detailTypeMap;
    }

    public List<RecordView> call() throws Exception {
        List<RecordView> resultList = new ArrayList<>();
        for (DetailView detailView : list) {
            RecordView view = buildRecordView(detailView,detailTypeMap);
            resultList.add(view);
        }
        return resultList;
    }
    
    public RecordView buildRecordView(DetailView detailView,Map<String,String> detailTypeMap){return new RecordView();}
    
}

 

posted @ 2022-12-22 16:44  涂山有雨  阅读(40)  评论(0编辑  收藏  举报