ThreadPoolExecutor创建线程池2021.12.15

ThreadPoolExecutor创建线程池2021.12.15,第1张

ThreadPoolExecutor创建线程池2021.12.15

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

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

二、使用ThreadPoolExecutor来创建线程池
依赖

 
        
            com.google.guava
            guava
            22.0
        
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;


@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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5673172.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存