JAVA线程池开发


1.java给我们自带了4种线程池
newSingleThreadExexcutor:单线程数的线程池(核心线程数=最大线程数=1)
newFixedThreadPool:固定线程数的线程池(核心线程数=最大线程数=自定义)
newCacheThreadPool:可缓存的线程池(核心线程数=0,最大线程数=Integer.MAX_VALUE)
newScheduledThreadPool:支持定时或周期任务的线程池(核心线程数=自定义,最大线程数=Integer.MAX_VALUE
使用方式:
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.execute(() -> {
  // 业务逻辑
});

2. 往往我们需要根据业务实际情况自己定义线程池

2.1 创建线程池类:

package com.xxx.xxx.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
public class MyThreadPoolConfig {

@Bean("MyThreadPoolExecutor")
public ThreadPoolExecutor threadPoolExecutor() {
return new ThreadPoolExecutor(
//核心线程数量
16,
//最大线程数量
16,
//最大存活时间
60,
//单位秒
TimeUnit.SECONDS,
//队列类型及大小,
new LinkedBlockingDeque<>(3200),
//线程工厂,构建线程
Executors.defaultThreadFactory(),
//任务具有策略
new ThreadPoolExecutor.AbortPolicy());
}
}

2.2 使用示例:
@Resource
private ThreadPoolExecutor myThreadPoolExecutor;
## 方法中调用
myThreadPoolExecutor.execute(() -> {
  // 业务逻辑
})
posted @   美宰可#F22  阅读(31)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示