直接上代碼
配置
定義一個配置類
創建一個springboot能掃描到的地方創建一個線程池配置類
配置信息
package com.example.demonew.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;@Configuration //表明是配置類,springboot會來掃描
public class ThreadPoolConfig {@Bean(name="taskExecutor") //配置bean對象交給springboot容器給我們管理,這時候就相當于創建了一個單例線程池名字為taskExecutorpublic Executor taskExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();executor.setCorePoolSize(5);executor.setMaxPoolSize(10);executor.setQueueCapacity(100);executor.initialize();return executor;}@Bean("poolExecutor") //配置第二個線程池public Executor poolExecutor() {ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();//設置線程池參數信息taskExecutor.setCorePoolSize(10);taskExecutor.setMaxPoolSize(50);taskExecutor.setQueueCapacity(200);taskExecutor.setKeepAliveSeconds(60);taskExecutor.setThreadNamePrefix("myExecutor2--");taskExecutor.setWaitForTasksToCompleteOnShutdown(true);taskExecutor.setAwaitTerminationSeconds(60);//修改拒絕策略為使用當前線程執行taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//初始化線程池taskExecutor.initialize();return taskExecutor;}
}
實現
package com.example.demonew.service;import com.example.demonew.config.ThreadPoolConfig;
import jakarta.annotation.Resource;import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;import java.util.concurrent.Executors;@Service
public class TestServiceImpl implements TestService{@Resource(name = "taskExecutor") //指定注入的bean 可以切換成poolExecutorprivate ThreadPoolTaskExecutor executor;@Overridepublic String test() {ThreadPoolTaskExecutor taskExecutor = executor;// 獲取線程池信息int activeCount = taskExecutor.getActiveCount();int corePoolSize = taskExecutor.getCorePoolSize();int poolSize = taskExecutor.getPoolSize();taskExecutor.execute(()->{System.out.printf(activeCount+"--"+corePoolSize);});return null;}
}
結果
@Resource(name = "taskExecutor") //指定注入的bean 可以切換成poolExecutor
private ThreadPoolTaskExecutor executor;
@Resource(name = "poolExecutor")
private ThreadPoolTaskExecutor executor;
切換成功