如何判断线程池任务有没有执行完

package com.example.demo;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @author yg
 * @description TODO
 * @date 2023-06-15 22:56
 */
@Slf4j
public class CountDownTest {

    private static final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("yg-countdown-%d").build();
    static ThreadPoolExecutor executor = new ThreadPoolExecutor(
            4,
            5,
            30,
            TimeUnit.SECONDS, new ArrayBlockingQueue<>(3),
            threadFactory,
            new ThreadPoolExecutor.CallerRunsPolicy()
    );

    public static void main(String[] args) throws InterruptedException {

        int xiancheng = 9;
        CountDownLatch countDownLatch = new CountDownLatch(xiancheng);
        for (int i = 0; i < xiancheng; i++) {
            executor.submit(() -> {
                log.info("线程:{} , 正在运行", Thread.currentThread().getName());
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        log.info("线程都完了--------------");
    }
}

使用CountDownLatch 来判断,运行结果如下

com.example.demo.CountDownTest
23:33:06.958 [yg-countdown-0] INFO com.example.demo.CountDownTest - 线程:yg-countdown-0 , 正在运行
23:33:06.958 [main] INFO com.example.demo.CountDownTest - 线程:main , 正在运行
23:33:06.962 [yg-countdown-0] INFO com.example.demo.CountDownTest - 线程:yg-countdown-0 , 正在运行
23:33:06.962 [yg-countdown-0] INFO com.example.demo.CountDownTest - 线程:yg-countdown-0 , 正在运行
23:33:06.962 [yg-countdown-0] INFO com.example.demo.CountDownTest - 线程:yg-countdown-0 , 正在运行
23:33:06.958 [yg-countdown-3] INFO com.example.demo.CountDownTest - 线程:yg-countdown-3 , 正在运行
23:33:06.958 [yg-countdown-4] INFO com.example.demo.CountDownTest - 线程:yg-countdown-4 , 正在运行
23:33:06.958 [yg-countdown-2] INFO com.example.demo.CountDownTest - 线程:yg-countdown-2 , 正在运行
23:33:06.958 [yg-countdown-1] INFO com.example.demo.CountDownTest - 线程:yg-countdown-1 , 正在运行
23:33:06.962 [main] INFO com.example.demo.CountDownTest - 线程都完了--------------

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