其他分享
首页 > 其他分享> > ThreadPoolExecutor创建线程池2021.12.15

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

标签:java,15,2021.12,util,concurrent,线程,import,ThreadPoolExecutor
来源: https://blog.csdn.net/qq_28865843/article/details/121947494