当前位置: 首页 > wzjs >正文

英德住房和城乡建设部网站黑科技引流软件是真的吗

英德住房和城乡建设部网站,黑科技引流软件是真的吗,做团队网站源码有哪些,上海做网站费用文章目录 Spring Boot 中多线程工具类的配置与使用:基于 YAML 配置文件1. 为什么需要多线程工具类?2. 实现步骤2.1 添加依赖2.2 配置线程池参数2.3 创建配置类2.4 创建线程池工具类2.5 使用线程池工具类2.6 测试线程池工具类 3. 配置文件的灵活性4. 总结…

文章目录

      • Spring Boot 中多线程工具类的配置与使用:基于 YAML 配置文件
      • 1. 为什么需要多线程工具类?
      • 2. 实现步骤
        • 2.1 添加依赖
        • 2.2 配置线程池参数
        • 2.3 创建配置类
        • 2.4 创建线程池工具类
        • 2.5 使用线程池工具类
        • 2.6 测试线程池工具类
      • 3. 配置文件的灵活性
      • 4. 总结


Spring Boot 中多线程工具类的配置与使用:基于 YAML 配置文件

在现代软件开发中,多线程编程是提高系统性能和并发处理能力的重要手段。Spring Boot 作为一款流行的 Java 开发框架,提供了强大的多线程支持。本文将详细介绍如何在 Spring Boot 中结合 YAML 配置文件,实现一个灵活、可配置的多线程工具类。


1. 为什么需要多线程工具类?

在多线程编程中,直接使用 ThreadExecutorService 可能会导致以下问题:

  • 资源浪费:频繁创建和销毁线程会消耗大量系统资源。
  • 难以管理:线程的生命周期和状态难以监控和维护。
  • 配置不灵活:线程池的参数(如核心线程数、队列容量等)硬编码在代码中,难以动态调整。

通过封装一个多线程工具类,并结合 YAML 配置文件,可以解决上述问题,使多线程编程更加高效和灵活。


2. 实现步骤

2.1 添加依赖

pom.xml 中添加 Spring Boot 的依赖:

<dependencies><!-- Spring Boot Starter --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><!-- Spring Boot Configuration Processor --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency>
</dependencies>
2.2 配置线程池参数

application.yml 中定义线程池的配置参数:

thread-pool:core-pool-size: 10 # 核心线程数max-pool-size: 20 # 最大线程数queue-capacity: 100 # 任务队列容量keep-alive-time: 60 # 线程空闲时间(秒)thread-name-prefix: "custom-thread-" # 线程名称前缀
2.3 创建配置类

通过 @ConfigurationProperties 注解将 YAML 文件中的配置映射到 Java 类中:

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;@Component
@ConfigurationProperties(prefix = "thread-pool")
public class ThreadPoolProperties {private int corePoolSize;private int maxPoolSize;private int queueCapacity;private long keepAliveTime;private String threadNamePrefix;// Getters and Setterspublic int getCorePoolSize() {return corePoolSize;}public void setCorePoolSize(int corePoolSize) {this.corePoolSize = corePoolSize;}public int getMaxPoolSize() {return maxPoolSize;}public void setMaxPoolSize(int maxPoolSize) {this.maxPoolSize = maxPoolSize;}public int getQueueCapacity() {return queueCapacity;}public void setQueueCapacity(int queueCapacity) {this.queueCapacity = queueCapacity;}public long getKeepAliveTime() {return keepAliveTime;}public void setKeepAliveTime(long keepAliveTime) {this.keepAliveTime = keepAliveTime;}public String getThreadNamePrefix() {return threadNamePrefix;}public void setThreadNamePrefix(String threadNamePrefix) {this.threadNamePrefix = threadNamePrefix;}
}
2.4 创建线程池工具类

在工具类中注入 ThreadPoolProperties,并根据配置创建线程池:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.*;@Component
public class ThreadPoolUtil {private ThreadPoolExecutor threadPool;@Autowiredprivate ThreadPoolProperties threadPoolProperties;/*** 初始化线程池*/@PostConstructpublic void init() {threadPool = new ThreadPoolExecutor(threadPoolProperties.getCorePoolSize(),threadPoolProperties.getMaxPoolSize(),threadPoolProperties.getKeepAliveTime(),TimeUnit.SECONDS,new LinkedBlockingQueue<>(threadPoolProperties.getQueueCapacity()),new ThreadFactory() {private final AtomicInteger threadNumber = new AtomicInteger(1);@Overridepublic Thread newThread(Runnable r) {return new Thread(r, threadPoolProperties.getThreadNamePrefix() + threadNumber.getAndIncrement());}},new ThreadPoolExecutor.AbortPolicy() // 拒绝策略:直接抛出异常);}/*** 提交任务(Runnable)** @param task 任务*/public void execute(Runnable task) {threadPool.execute(task);}/*** 提交任务(Callable)** @param task 任务* @param <T>  返回值类型* @return Future 对象*/public <T> Future<T> submit(Callable<T> task) {return threadPool.submit(task);}/*** 关闭线程池(等待所有任务完成)*/@PreDestroypublic void shutdown() {if (threadPool != null) {threadPool.shutdown();try {if (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) {threadPool.shutdownNow();}} catch (InterruptedException e) {threadPool.shutdownNow();Thread.currentThread().interrupt();}}}/*** 获取线程池状态** @return 线程池状态信息*/public String getThreadPoolStatus() {if (threadPool == null) {return "Thread pool is not initialized.";}return String.format("Pool Status: [CorePoolSize: %d, ActiveThreads: %d, CompletedTasks: %d, QueueSize: %d]",threadPool.getCorePoolSize(),threadPool.getActiveCount(),threadPool.getCompletedTaskCount(),threadPool.getQueue().size());}
}
2.5 使用线程池工具类

在业务代码中注入 ThreadPoolUtil,并提交任务:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class TaskService {@Autowiredprivate ThreadPoolUtil threadPoolUtil;public void runTask() {// 提交 Runnable 任务threadPoolUtil.execute(() -> {System.out.println("Runnable task is running.");});// 提交 Callable 任务并获取结果Future<String> future = threadPoolUtil.submit(() -> {Thread.sleep(1000);return "Callable task result";});try {System.out.println("Callable task result: " + future.get());} catch (InterruptedException | ExecutionException e) {e.printStackTrace();}// 打印线程池状态System.out.println(threadPoolUtil.getThreadPoolStatus());}
}
2.6 测试线程池工具类

编写单元测试,验证线程池的功能:

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
public class ThreadPoolUtilTest {@Autowiredprivate TaskService taskService;@Testpublic void testThreadPool() {taskService.runTask();}
}

3. 配置文件的灵活性

通过 application.yml 配置文件,可以灵活调整线程池的参数,而无需修改代码。例如:

  • 调整核心线程数:

    thread-pool:core-pool-size: 20
    
  • 调整任务队列容量:

    thread-pool:queue-capacity: 200
    
  • 调整线程名称前缀:

    thread-pool:thread-name-prefix: "app-thread-"
    

4. 总结

通过将线程池的配置参数提取到 application.yml 中,并结合 Spring Boot 的依赖注入机制,我们可以实现一个灵活、可配置的多线程工具类。这种方式不仅提高了代码的可维护性,还能根据实际需求动态调整线程池的行为,是 Spring Boot 项目中管理多线程任务的推荐做法。希望本文能帮助你更好地理解和应用 Spring Boot 中的多线程编程技术!

http://www.dtcms.com/wzjs/177482.html

相关文章:

  • 怎么增加网站反链引擎优化seo
  • 怎么建设一个优秀的网站网站建设对企业品牌价值提升的影响
  • 建设银行新加坡分行网站优化大师班级优化大师
  • 大良营销网站建设流程班级优化大师免费下载电脑版
  • 做机械比较好的外贸网站幽默软文广告经典案例
  • 站长工具乱码短视频seo系统
  • 微信服务号可以做万网站么成都营销型网站制作
  • 自建的电子网站如何做推广怎样做网站的优化、排名
  • 做网站如何语音对话属于网络营销特点的是
  • 单页面网站有哪些内容沈阳专业seo
  • 计算机系部网站开发背景跨境电商培训
  • 深圳知名网站建设供应百度小说官网
  • 游戏源码 wordpress郑州seo培训
  • 网页具有动画网站建设技术泉州百度推广咨询
  • 做外贸需要什么网站百度账号管家
  • 中国商机创业网seo网站排名软件
  • 厦门做网站哪家强如何在百度上发布广告
  • 太原网站上排名51网站统计
  • 陕西汽车网站建设seo工作内容有哪些
  • 个人备案网站内不能出现什么内容电子报刊的传播媒体是什么
  • 昆明网站制作推荐360站长工具
  • 文库网站开发建设南京seo代理
  • 厦门网站建设电话廊坊百度快照优化哪家服务好
  • 网站建设代码结构百度高级检索入口
  • 旅游景点推广策划方案太原关键词排名优化
  • 宿城区建设局网站互联网营销是干什么
  • 哪里可以做外贸网站站长检测工具
  • 精品电商网站建设技术优化seo
  • 凡科怎么做网站aso网站
  • 乌鲁木齐网站建设哪家好百度收录入口提交