SpringBoot线程池工具类

1.@Component注解将ThreadPoolUtil注入spring容器
2.容器启动后会首先执行@PostConstruct注解的initProcessorThreadPool方法,该方法初始化线程池配置
3.CountDownLatch count = new CountDownLatch(子线程数量);
使用多线程时,由于子线程都是异步执行的,所以要等所有子线程结束的话,可以用CountDownLatch阻塞主线程,子线程结束时通过countDown()方法减少计数值,切记countDown()要放在finally中,以防子线程异常中断导致的主线程一直阻塞;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.concurrent.*;

/**
 * @author JHL
 * @version 1.0
 * @date 2022/10/10 19:01
 * @since : JDK 11
 */
@Component
public class ThreadPoolUtil {

    @Value("${cutsomThreadPool.corePoolSize:10}")
    private Integer corePoolSize;

    @Value("${cutsomThreadPool.maximumPoolSize:10}")
    private Integer maximumPoolSize;

    private static ThreadPoolExecutor executor;

    @PostConstruct
    public void initProcessorThreadPool() {
        executor = new ThreadPoolExecutor(
                corePoolSize
                , maximumPoolSize
                , 60
                , TimeUnit.SECONDS
                , new SynchronousQueue<>(true)
                , new BlockRejectedExecutionHandler()
        );
    }

    public static <T> Future<T> submit(Callable<T> task) {
        return executor.submit(task);
    }

    public static void submit(Runnable runnable) {
        executor.submit(runnable);
    }

    private static class BlockRejectedExecutionHandler implements RejectedExecutionHandler {

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            try {
                executor.getQueue().put(r);
            } catch (InterruptedException ignored) {
            }
        }
    }
}

posted @ 2022-10-10 19:15  黄河大道东  阅读(71)  评论(0编辑  收藏  举报