spring线程池ThreadPoolTaskExecutor
1. 自定义yml属性配置
thread: pool: corePoolSize: 5 maxPoolSize: 10 queueCapacity: 10 keepAliveSeconds: 120
2.自定义线程池配置类
@Configuration //配置类 @EnableAsync //开线线程异步支持 public class MyThreadPoolExecutor { @Autowired private ThreadPoolProperty threadPoolProperties; @Bean(name = "threadPoolTaskExecutor") //为线程使用提供实例 public ThreadPoolTaskExecutor threadPoolTaskExecutor(){ ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); threadPoolTaskExecutor.setCorePoolSize(threadPoolProperties.getCorePoolSize()); threadPoolTaskExecutor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize()); threadPoolTaskExecutor.setQueueCapacity(threadPoolProperties.getQueueCapacity()); threadPoolTaskExecutor.setKeepAliveSeconds(threadPoolProperties.getKeepAliveSeconds()); threadPoolTaskExecutor.setThreadNamePrefix("thread-pool-"); //方便查看 return threadPoolTaskExecutor; } }
3. 使用@Async创建线程实例
@Service
@Slf4j
public class AssetScanServiceImpl implements AssetScanService {
@Async("threadPoolTaskExecutor")
public void test1() throws InterruptedException {
log.info("test1 start....");
Thread.sleep(3000);
log.info("test1 end....");
}
@Async("threadPoolTaskExecutor")
public void test2() throws InterruptedException {
log.info("test2 start....");
Thread.sleep(3000);
log.info("test2 end....");
}
}
如下方式会使@Async失效
一、异步方法使用static修饰
二、异步类没有使用@Component注解(或其他注解)导致spring无法扫描到异步类
三、异步方法不能与异步方法在同一个类中
四、类中需要使用@Autowired或@Resource等注解自动注入,不能自己手动new对象
五、如果使用SpringBoot框架必须在启动类中增加@EnableAsync注解
六、在Async 方法上标注@Transactional是没用的。 在Async 方法调用的方法上标注@Transactional 有效。
七、调用被@Async标记的方法的调用者不能和被调用的方法在同一类中不然不会起作用!!!!!!!
八、使用@Async时要求是不能有返回值的不然会报错的 因为异步要求是不关心结果的
----------------------------
这样使用
@Service @Slf4j public class AssetScanServiceImpl implements AssetScanService { @Autowired private MyThreadPoolExecutor myThreadPoolExecutor; //引入实例 @Override public void beginScan(List<String>list) { ThreadPoolTaskExecutor executor = myThreadPoolExecutor.threadPoolTaskExecutor(); for (String command : list) {//循环开启多线程 executor.execute(() -> { try { Process exec = Runtime.getRuntime().exec(command); StringBuffer stringBuffer = new StringBuffer(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(exec.getInputStream(), Charset.forName("GBK"))); //使用拼接一行在用正则取值 String str=""; while ((str=bufferedReader.readLine())!=null){ stringBuffer.append(str); } log.info(Thread.currentThread().getName()+stringBuffer); } catch (IOException e) { e.printStackTrace(); log.error("脚本执行异常"); } }); } // executor.setWaitForTasksToCompleteOnShutdown(true);//等待所有任务执行完关闭线程池 // executor.shutdown(); }
分类:
多线程
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库