java多线程同时执行方法

public BizWashoutDetail getObject(BizWashoutDetail qo) {
    List list = getBaseMapper().queryList(qo);
    if (list.size() <= 0) {
        return new BizWashoutDetail();
    }
    BizWashoutDetail object = list.get(0);

    CountDownLatch latch = new CountDownLatch(5); // 创建一个CountDownLatch,用于协调线程的执行和等待结果
    ConcurrentHashMap resultMap = new ConcurrentHashMap<>(); // 创建一个用于存储结果的共享对象

    ExecutorService executorService = Executors.newFixedThreadPool(5); // 创建一个固定大小为5的线程池

    // 提交第一个查询
    executorService.submit(() -> {
        Double result = bizWashoutDetailMapper.getCurRestorationAmount(qo);
        resultMap.put("a", result);
        latch.countDown(); // 调用countDown()方法,表示已完成一个查询
    });

    // 提交第二个查询
    executorService.submit(() -> {
        Double result = bizWashoutDetailMapper.getLjRestorationAmount(qo);
        resultMap.put("b", result);
        latch.countDown();
    });

    // 提交第三个查询
    executorService.submit(() -> {
        Double result = bizWashoutDetailMapper.getCurAmountOfLoss(qo);
        resultMap.put("c", result);
        latch.countDown();
    });

    // 提交第四个查询
    executorService.submit(() -> {
        Double result = bizWashoutDetailMapper.getLjAmountOfLoss(qo);
        resultMap.put("d", result);
        latch.countDown();
    });

    try {
        latch.await(); // 主线程等待所有查询完成

        // 获取结果并设置到对象中
        Double a = resultMap.get("a");
        Double b = resultMap.get("b");
        Double c = resultMap.get("c");
        Double d = resultMap.get("d");

        if (a != null) {
            object.setCurRestorationAmount(a);
        }
        if (b != null) {
            object.setLjRestorationAmount(b);
        }
        if (c != null) {
            object.setCurAmountOfLoss(c);
        }
        if (d != null) {
            object.setLjAmountOfLoss(d);
        }
    } catch (InterruptedException e) {
        // 处理异常
    } finally {
        executorService.shutdown(); // 关闭线程池
    }

    return object;
}

你可能感兴趣的:(java,python,windows)