Java中使用线程池进行多线程执行结果汇总

 

实现过程

创建线程池

首先创建一个线程池,这一步骤大同小异

复制代码
package cn.com.wind.common;


import lombok.AllArgsConstructor;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * @Author qymeng
 * @Date 2021/8/19
 * @Description 线程池
 */
@AllArgsConstructor
public class TaskExecutePool {

    public ThreadPoolExecutor threadPoolExecutor;

    private TaskExecutePool() {
        threadPoolExecutor = new ThreadPoolExecutor(20,//线程池大小
                30, //默认最大线程
                5, //空闲线程保持时间
                TimeUnit.SECONDS,//单位秒
                new LinkedBlockingDeque<>(200),//,等待队列大小200
                new ThreadPoolExecutor.CallerRunsPolicy());//拒绝策略:
    }

    /**
     * 获取实例
     *
     * @return
     */
    public static TaskExecutePool getInstance() {
        return new TaskExecutePool();
    }
}
复制代码

创建一个执行任务的类

其中process中存放业务逻辑

复制代码
package cn.com.wind.common;

import cn.com.wind.controller.dto.IndexAlignDto;
import cn.com.wind.controller.vo.alignvo.Lbls;
import cn.com.wind.service.IndexAlign.IndexAlignService;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * @Author qymeng
 * @Date 2022/8/19
 * @Description
 */
@Slf4j
public class CurrentIndexAlignTask implements Callable<List<Lbls>> {

    private final IndexAlignDto dto;

    private final IndexAlignService indexAlignService;

    public CurrentIndexAlignTask(IndexAlignDto dto, IndexAlignService indexAlignService) {
        this.dto = dto;
        this.indexAlignService = indexAlignService;
    }


    private List<Lbls> process(){
        return indexAlignService.indexAlignByGraph(dto);
    }

    @Override
    public List<Lbls> call() throws Exception {
        return process();
    }
}
复制代码

编写测试用例

测试用例为了方便就写到了创建线程池的那个类里,在它里面添加一个主方法用来测试,下面是完成线程池类代码

 

复制代码
@PostMapping("/indexAlignByGraph")
    public CommonResp<IndexAlignVo> currentIndexAlignByGraph(@RequestBody List<IndexAlignDto> dtoList) throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();
        IndexAlignVo indexAlignVo = new IndexAlignVo();
        List<Prediction> predictions = new ArrayList<>();

        TaskExecutePool executor = TaskExecutePool.getInstance();
        List<Future<List<Lbls>>> futureList = new LinkedList<>();

        for (IndexAlignDto dto : dtoList) {
            List<IndexAlignDto.Entities> entities = dto.getEntities();

            String source = dto.getSource();
//            如果为表格,调用预处理接口将属性补齐
            if (source != null && source.equals("table")) {
                entities = indexAlignService.indicatorEleType(entities);
                dto.setEntities(entities);
            }
            CurrentIndexAlignTask task = new CurrentIndexAlignTask(dto, indexAlignService);
            Future<List<Lbls>> submit = executor.threadPoolExecutor.submit(task);
            futureList.add(submit);

        }

        for (Future<List<Lbls>> future : futureList) {
            while (true) {
                if (future.isDone() && !future.isCancelled()) {
                    Prediction prediction = new Prediction();
                    List<Data> dataList = new ArrayList<>();
                    Data data = new Data();
                    List<Lbls> topN = future.get();
                    data.setLbls(topN);
                    dataList.add(data);
                    prediction.setData(dataList);
                    predictions.add(prediction);
                    break;
                }
            }
        }
        indexAlignVo.setPrediction(predictions);
        executor.threadPoolExecutor.shutdown();
        log.info("调用知识图谱的耗时为:{}ms,其他逻辑的耗时为:{}ms,总耗时为:{}ms", graphTime, System.currentTimeMillis() - startTime - graphTime, System.currentTimeMillis() - startTime);
        return CommonResp.ok(indexAlignVo);
    }
复制代码

 

posted @   Mikey-  阅读(875)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
点击右上角即可分享
微信分享提示