ThreadPoolExecutor创建线程池2021.12.15

一、阿里不允许这样创建线程池

ExecutorService executor = Executors.newFixedThreadPool(xcList.size());

二、使用ThreadPoolExecutor来创建线程池

package com.example.demo.test;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author xuhc7
 * @date 2021年12月15日 10:32
 */
@Configuration
public class ThreadConfiguration {
    private ThreadPoolExecutor threadPoolExecutor;
    @Bean
    public ThreadPoolExecutor getThreadPool(){
        //给线程命名
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat( "test-thread-%d").build();
        //设置线程池参数
        threadPoolExecutor = new ThreadPoolExecutor(5, 10240, 100,
                TimeUnit.SECONDS, new ArrayBlockingQueue<>(10240), namedThreadFactory);
        //设置拒绝策略
        threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
        return threadPoolExecutor;
    }


}

线程运行结果test-thread-0,test-thread-1

上一篇:义乌集训7.14 contest 7题解


下一篇:Spring Boot中使用Swagger3生成API文档