阅读 277

springboot创建线程池的两种方式小结

这篇文章主要介绍了springboot创建线程池的两种方式小结,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

目录
  • springboot创建线程池两种方式

    • 1.使用static代码块创建

    • 2.使用@Configuration @bean注解,程序启动时创建

  • springboot开启线程池

    • 定义线程池

    • 使用

springboot创建线程池两种方式

1.使用static代码块创建

这样的方式创建的好处是当代码用到线程池的时候才会初始化核心线程数

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class HttpApiThreadPool {
 /** 获取当前系统的CPU 数目*/
 static int cpuNums = Runtime.getRuntime().availableProcessors();
 /** 线程池核心池的大小*/
 private static int corePoolSize = 10;
 /** 线程池的最大线程数*/
 private static int maximumPoolSize = cpuNums * 5;
 public static ExecutorService httpApiThreadPool = null;
  
 /**
  * 静态方法
  */
 static{
  System.out.println("创建线程数:"+corePoolSize+",最大线程数:"+maximumPoolSize);
  //建立10个核心线程,线程请求个数超过20,则进入队列等待
  httpApiThreadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 0L,
  TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(100),new ThreadFactoryBuilder().setNameFormat("PROS-%d").build());
 }
}

使用方法

1
2
3
public static void main(String[] args) {
 HttpApiThreadPool.httpApiThreadPool.execute(()->System.out.println("测试"));
}

注意:

1.不能使用Executors的方法创建线程池,这个是大量的生产事故得出来的结论

2.maximumPoolSize本程序使用的是cup数的5倍,你可以看你实际情况用

3.new ThreadFactoryBuilder().setNameFormat("PROS-%d").build() 给每个线程已名字,可以方便调试

2.使用@Configuration @bean注解,程序启动时创建


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Configuration
public class TreadPoolConfig {
 private Logger logger = LoggerFactory.getLogger(TreadPoolConfig.class);
 /** 获取当前系统的CPU 数目*/
 int cpuNums = Runtime.getRuntime().availableProcessors();
 /** 线程池核心池的大小*/
 private  int corePoolSize = 10;
 /** 线程池的最大线程数*/
 private  int maximumPoolSize = cpuNums * 5;
  
    /**
     * 消费队列线程
     * @return
     */
    @Bean(value = "httpApiThreadPool")
    public ExecutorService buildHttpApiThreadPool(){
     logger.info("TreadPoolConfig创建线程数:"+corePoolSize+",最大线程数:"+maximumPoolSize);
        ExecutorService pool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 0L,
 TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(100),new ThreadFactoryBuilder().setNameFormat("PROS-%d").build());
        return pool ;
 }
}

使用方法

1
2
3
4
5
6
7
  //注入
   @Resource
private TreadPoolConfig treadPoolConfig;
  //调用
  public void test() {
 treadPoolConfig.buildHttpApiThreadPool().execute(()->System.out.println("tre"));
}

现在两种线程池的创建方法已经介绍完了。

springboot开启线程池

定义线程池

定义的位置,要在启动类的子包或者同级目录中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import lombok.Data;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
@Data
@Configuration
@EnableAsync //开启异步请求
public class ThreadPoolConfig {
   
    private static final int corePoolSize = 10;   // 核心线程数(默认线程数)
    private static final int maxPoolSize = 100;   // 最大线程数
    private static final int keepAliveTime = 10// 允许线程空闲时间(单位:默认为秒)
    private static final int queueCapacity = 500; // 缓冲队列数
    /**
     * 默认异步线程池
     * @return
     */
    @Bean("taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor(){
        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        pool.setThreadNamePrefix("--------------全局线程池-----------------");
        pool.setCorePoolSize(corePoolSize);
        pool.setMaxPoolSize(maxPoolSize);
        pool.setKeepAliveSeconds(keepAliveTime);
        pool.setQueueCapacity(queueCapacity);
        // 直接在execute方法的调用线程中运行
        pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化
        pool.initialize();
        return pool;
    }
}

使用

直接在需要异步执行的方法上加注解

1
@Async("taskExecutor")

以上为个人经验,希望能给大家一个参考

原文链接:https://blog.csdn.net/qq_34204599/article/details/106013204


文章分类
百科问答
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐