在工作过程中经常遇到需要处理非依赖性的http接口请求或者非依赖型的查库入库操作
在这种情况下,为了提升性能,用多线程来处理性能更佳

import java.util.*;
import java.util.concurrent.*;
private static final int THREAD_INIT_COUNT = 10;
public static void main(String[] args) {
    Map<String,String[]> parameterMap=要处理的多任务数据
    handleAssessScore(parameterMap);
}
private void handleAssessScore(Map<String,String[]> parameterMap){
    Set<String> assesss = parameterMap.keySet();
    if (assesss.size() == 0) {
        return;
    }
    final BlockingQueue<String> queue = new ArrayBlockingQueue<String>(assesss.size());
    for (String record : assesss) {
        queue.offer(record);
    }
    ExecutorService executorService = Executors.newFixedThreadPool(THREAD_INIT_COUNT);
    final CountDownLatch countDownLatch = new CountDownLatch(assesss.size());
    for (int i = 0; i < THREAD_INIT_COUNT; i++) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (queue.isEmpty()) {
                        break;
                    }
                    String assess = "";
                    try {
                        assess = queue.take();
                    } catch (InterruptedException e1) {
                        logger.error("计算评估图搜算法评分,日期{},uuId->{},e->{}", new Date(), assess, e1);
                    }
                    try {
                        //TODO 真正的函数调用处
                        System.out.println("key-->"+assess+" ;value-->"+parameterMap.get(assess)[0]);
                        logger.info("调用计算评估图搜算法评分,日期{},uuId->{}", new Date(), assess);
                    } catch (Exception e) {
                        logger.error("调用计算评估图搜算法评分异常,日期{},uuId->{},e->{}", new Date(), assess, e);
                    } finally {
                        countDownLatch.countDown();
                    }
                }
            }
        });
    }
    while (countDownLatch.getCount() != 0) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    executorService.shutdownNow();
    logger.info("调用计算评估图搜算法评分 end.");
}

更多推荐