java并发执行代码获取数据库数据

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

/**
 * 并发工具类
 *
 * @author huayal
 * @since 2022-12-22
 *
 */
public class ConcurrentUtil {
    /**
     * 执行任务
     *
     * @param executorService ExecutorService
     * @param callable 回调
     * @param  返回的结果集Future泛型
     * @return Future泛型
     */
    public static  Future doJob(ExecutorService executorService, Callable callable) {
        return executorService.submit(callable);
    }

    /**
     * 获取结果集,执行时会阻塞直到有结果,中间的异常不会被静默
     *
     * @param future Future
     * @param  返回的结果集泛型
     * @return T
     */
    public static  T futureGet(Future future) {
        try {
            return future.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
}

        (服务层的方法中代码:关键步骤)
        //开启几个线程池:6
        ExecutorService executorService = Executors.newFixedThreadPool(6);
        //执行的方法:getMissNum(oneEnd, orgId)和getReplantNum(oneStart, oneEnd, orgId)
        Future futureMissNumOne = ConcurrentUtil.doJob(executorService, () -> getMissNum(oneEnd, orgId));
        Future futureReplantNumOne = ConcurrentUtil.doJob(executorService, () -> getReplantNum(oneStart, oneEnd, orgId));
        //获取到得数据missNum1  replantNum1 
        Integer missNum1 = ConcurrentUtil.futureGet(futureMissNumOne);
        Integer replantNum1 = ConcurrentUtil.futureGet(futureReplantNumOne);
        
 

    //向数据库获取数据的方法
    public Integer getMissNum(LocalDate monthEnd, Integer orgId){
        return mapper.getMissNum(monthEnd, orgId);
    }

    public Integer getReplantNum(LocalDate monthStart,LocalDate monthEnd, Integer orgId){
        return mapper.getReplantNum(monthStart, monthEnd, orgId);
    }

你可能感兴趣的:(java,开发语言)