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 { /* @Autowired private MyThreadPoolExecutor myThreadPoolExecutor;*/ @Override @Async("threadPoolTaskExecutor") //指定线程池 public void beginScan() { //开启线程池启动任务每个任务为一个线程池 为了演示方便为每个指令一个线程 String baidu = "ping www.baidu.com"; String alibaba = "ping www.alibaba.com"; String google = "ping www.google.com"; ArrayList<String> list = new ArrayList<>(); Collections.addAll(list,baidu,alibaba,google); // 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(); } }
标签:String,spring,threadPoolProperties,线程,new,threadPoolTaskExecutor,ThreadPoolTaskE From: https://www.cnblogs.com/caoaman/p/17399365.html