多线程 ThreadPoolTaskExecutor 应用

1.如何判断线程池所有任务是否执行完毕

package com.vipsoft.web;
 
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.io.File;
import java.util.concurrent.CountDownLatch;

@SpringBootTest
public class ThreadTest {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Test
    void verification() throws Exception {
        File f = new File("D:\\Logs\\");
        CountDownLatch countDownLatch = new CountDownLatch(f.listFiles().length);
        for (File file : f.listFiles()) {
            if (file.isFile()) { 
                String fileName = file.getName(); 
                try {
                    UserInfo userInfo = new UserInfo();
                    userInfo.getName("Name "+i);
                    threadExecutor(countDownLatch, userInfo); 
                    logger.info("发出执行请求 => {}", fileName);
                } catch (Exception ex) {
                    logger.error("异常 {}", fileName);
                    logger.error(ex.getMessage(), ex);
                }
            }
        }
        //阻塞当前线程,直到倒数计数器倒数到0
        try { 
            logger.info("阻塞当前线程,直到倒数计数器倒数到0");
            countDownLatch.await();
            logger.info("全部处理完成");
        } catch (Exception ex) {
            logger.error("阻塞当前线程异常{}", ex.getMessage(), ex);
        }
    }

    void threadExecutor(CountDownLatch countDownLatch, UserInfo userInfo) {
        try {
            threadPoolTaskExecutor.execute(() -> {
                try {
                    logger.info("线程名称{} {}", Thread.currentThread().getName(), userInfo.getName());
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    //很关键, 无论上面程序是否异常必须执行countDown,否则await无法释放
                    countDownLatch.countDown();
                }
            });
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
    }
}

 

posted @ 2022-05-11 10:27  VipSoft  阅读(143)  评论(0编辑  收藏  举报