一、阿里不允许这样创建线程池
ExecutorService executor = Executors.newFixedThreadPool(xcList.size());
二、使用ThreadPoolExecutor来创建线程池
依赖
com.google.guava guava22.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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)