Spring线程池开发实战

本文提供了三个Spring多线程开发的例子,由浅入深,由于例子一目了然,所以并未做过多的解释。诸位一看便知。

 

前提条件:

1)在Eclipse创建一个Java项目,我取名为SpringThreadDemo。
2)项目所需的JAR包如图所示:
 

下面开始。

 

注:项目源码已经托管到GitHub,地址:https://github.com/chszs/SpringThreadDemo

例子1:Spring结合Java线程。

通过继承Thread创建一个简单的Java线程,然后使用@Component让Spring容器管理此线程,Bean的范围必须是prototype,因此每个请求都会返回一个新实例,运行每个单独的线程。

PrintThread.java

 

[java]  view plain copy
 
  1. package com.chszs.thread;  
  2.   
  3. import org.springframework.stereotype.Component;  
  4. import org.springframework.context.annotation.Scope;  
  5.   
  6. @Component  
  7. @Scope("prototype")  
  8. public class PrintThread extends Thread{  
  9.         @Override  
  10.         public void run(){  
  11.                 System.out.println(getName() + " is running.");  
  12.                 try{  
  13.                         Thread.sleep(5000);  
  14.                 }catch(InterruptedException e){  
  15.                         e.printStackTrace();  
  16.                 }  
  17.                 System.out.println(getName() + " is running again.");  
  18.         }  
  19. }  

 

AppConfig.java

 

 

[java]  view plain copy
 
  1. package com.chszs.config;  
  2.   
  3. import org.springframework.context.annotation.ComponentScan;  
  4. import org.springframework.context.annotation.Configuration;  
  5.   
  6. @Configuration  
  7. @ComponentScan(basePackages="com.chszs.thread")  
  8. public class AppConfig {  
  9. }  

App.java

 

 

[java]  view plain copy
 
  1. package com.chszs;  
  2. import org.springframework.context.ApplicationContext;  
  3. import org.springframework.context.annotation.AnnotationConfigApplicationContext;  
  4.   
  5. import com.chszs.config.AppConfig;  
  6. import com.chszs.thread.PrintThread;  
  7.   
  8. public class App {  
  9.         public static void main(String[] args){  
  10.                 ApplicationContext ctx =   
  11.             new AnnotationConfigApplicationContext(AppConfig.class);  
  12.                 PrintThread printThread1 = (PrintThread)ctx.getBean("printThread");  
  13.                 printThread1.setName("Thread 1");  
  14.                   
  15.                 PrintThread printThread2 = (PrintThread)ctx.getBean("printThread");  
  16.                 printThread2.setName("Thread 2");  
  17.                   
  18.                 PrintThread printThread3 = (PrintThread)ctx.getBean("printThread");  
  19.                 printThread3.setName("Thread 3");  
  20.                   
  21.                 PrintThread printThread4 = (PrintThread)ctx.getBean("printThread");  
  22.                 printThread4.setName("Thread 4");  
  23.                   
  24.                 PrintThread printThread5 = (PrintThread)ctx.getBean("printThread");  
  25.                 printThread5.setName("Thread 5");  
  26.                   
  27.                 printThread1.start();  
  28.                 printThread2.start();  
  29.                 printThread3.start();  
  30.                 printThread4.start();  
  31.                 printThread5.start();  
  32.         }  
  33. }  

 

输出:

Thread 1 is running.
Thread 2 is running.
Thread 4 is running.
Thread 5 is running.
Thread 3 is running.
Thread 2 is running again.
Thread 1 is running again.
Thread 5 is running again.
Thread 4 is running again.
Thread 3 is running again.

 

 

例子2:Spring线程池结合非Spring托管Bean。

 

使用Spring的ThreadPoolTaskExecutor类创建一个线程池。执行线程无需受Spring容器的管理。

PrintTask.java

 

 

[java]  view plain copy
 
  1. package com.chszs.thread;  
  2.   
  3. public class PrintTask implements Runnable{  
  4.         String name;  
  5.         public PrintTask(String name){  
  6.                 this.name = name;  
  7.         }  
  8.         @Override  
  9.         public void run() {  
  10.                 System.out.println(name + " is running.");  
  11.                 try{  
  12.                         Thread.sleep(5000);  
  13.                 }catch(InterruptedException e){  
  14.                         e.printStackTrace();  
  15.                 }  
  16.                 System.out.println(name + " is running again.");  
  17.         }  
  18.           
  19. }  

Spring-Config.xml

 

 

[html]  view plain copy
 
  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  3.         xmlns:context="http://www.springframework.org/schema/context"  
  4.         xsi:schemaLocation="http://www.springframework.org/schema/beans  
  5.         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
  6.         http://www.springframework.org/schema/context  
  7.         http://www.springframework.org/schema/context/spring-context-3.1.xsd">  
  8.           
  9.         <bean id="taskExecutor"   
  10.         class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">  
  11.                 <property name="corePoolSize" value="5" />  
  12.                 <property name="maxPoolSize" value="10" />  
  13.                 <property name="WaitForTasksToCompleteOnShutdown" value="true" />  
  14.         </bean>  
  15. </beans>  


注意这个Spring配置文件的位置,如图所示:

 



App1.java

 

[java]  view plain copy
 
  1. package com.chszs;  
  2.   
  3. import org.springframework.context.ApplicationContext;  
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  5. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;  
  6.   
  7. import com.chszs.thread.PrintTask;  
  8.   
  9. public class App1 {  
  10.   
  11.         public static void main(String[] args) {  
  12.                 ApplicationContext ctx =   
  13.             new ClassPathXmlApplicationContext("resources/Spring-Config.xml");  
  14.                 ThreadPoolTaskExecutor taskExecutor =  
  15.             (ThreadPoolTaskExecutor)ctx.getBean("taskExecutor");  
  16.                 taskExecutor.execute(new PrintTask("Thread 1"));  
  17.                 taskExecutor.execute(new PrintTask("Thread 2"));  
  18.                 taskExecutor.execute(new PrintTask("Thread 3"));  
  19.                 taskExecutor.execute(new PrintTask("Thread 4"));  
  20.                 taskExecutor.execute(new PrintTask("Thread 5"));  
  21.                 // 检查活动的线程,如果活动线程数为0则关闭线程池  
  22.                 for(;;){  
  23.                         int count = taskExecutor.getActiveCount();  
  24.                         System.out.println("Active Threads : " + count);  
  25.                         try{  
  26.                                 Thread.sleep(1000);  
  27.                         }catch(InterruptedException e){  
  28.                                 e.printStackTrace();  
  29.                         }  
  30.                         if(count==0){  
  31.                                 taskExecutor.shutdown();  
  32.                                 break;  
  33.                         }  
  34.                 }  
  35.         }  
  36.   
  37. }  

 

输出:

 

Thread 1 is running.
Thread 2 is running.
Thread 3 is running.
Thread 4 is running.
Active Threads : 4
Thread 5 is running.
Active Threads : 5
Active Threads : 5
Active Threads : 5
Active Threads : 5
Active Threads : 5
Thread 4 is running again.
Thread 2 is running again.
Thread 3 is running again.
Thread 1 is running again.
Thread 5 is running again.
Active Threads : 0

作者:chszs,转载需注明。博客主页:http://blog.youkuaiyun.com/chszs

例子3:Spring线程池结合Spring托管Bean。


本例仍然使用ThreadPoolTaskExecutor类,并使用@Component注释声明Spring的托管Bean。
下面的例子PrintTask2是Spring的托管Bean,使用@Autowired注释简化代码。

 

PrintTask2.java

 

[java]  view plain copy
 
  1. package com.chszs.thread;  
  2.   
  3. import org.springframework.context.annotation.Scope;  
  4. import org.springframework.stereotype.Component;  
  5.   
  6. @Component  
  7. @Scope("prototype")  
  8. public class PrintTask2 implements Runnable {  
  9.         String name;  
  10.   
  11.         public void setName(String name) {  
  12.                 this.name = name;  
  13.         }  
  14.           
  15.         @Override  
  16.         public void run(){  
  17.                 System.out.println(name + " is running.");  
  18.                 try{  
  19.                         Thread.sleep(5000);  
  20.                 }catch(InterruptedException e){  
  21.                         e.printStackTrace();  
  22.                 }  
  23.                 System.out.println(name + " is running again.");  
  24.         }  
  25. }  

 

AppConfig.java

 

 

[java]  view plain copy
 
  1. package com.chszs.config;  
  2.   
  3. import org.springframework.context.annotation.Bean;  
  4. import org.springframework.context.annotation.ComponentScan;  
  5. import org.springframework.context.annotation.Configuration;  
  6. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;  
  7.   
  8. @Configuration  
  9. @ComponentScan(basePackages="com.chszs.thread")  
  10. public class AppConfig {  
  11.         @Bean  
  12.         public ThreadPoolTaskExecutor taskExecutor(){  
  13.                 ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();  
  14.                 pool.setCorePoolSize(5);  
  15.                 pool.setMaxPoolSize(10);  
  16.                 pool.setWaitForTasksToCompleteOnShutdown(true);  
  17.                 return pool;  
  18.         }  
  19. }  

 

App2.java

 

 

[java]  view plain copy
 
  1. package com.chszs;  
  2.   
  3. import org.springframework.context.ApplicationContext;  
  4. import org.springframework.context.annotation.AnnotationConfigApplicationContext;  
  5. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;  
  6.   
  7. import com.chszs.config.AppConfig;  
  8. import com.chszs.thread.PrintTask2;  
  9.   
  10. public class App2 {  
  11.         public static void main(String[] args) {  
  12.                 ApplicationContext ctx =   
  13.             new AnnotationConfigApplicationContext(AppConfig.class);  
  14.                 ThreadPoolTaskExecutor taskExecutor =  
  15.             (ThreadPoolTaskExecutor)ctx.getBean("taskExecutor");  
  16.                   
  17.                 PrintTask2 printTask1 = (PrintTask2)ctx.getBean("printTask2");  
  18.                 printTask1.setName("Thread 1");  
  19.                 taskExecutor.execute(printTask1);  
  20.                   
  21.                 PrintTask2 printTask2 = (PrintTask2)ctx.getBean("printTask2");  
  22.                 printTask2.setName("Thread 2");  
  23.                 taskExecutor.execute(printTask2);  
  24.                   
  25.                 PrintTask2 printTask3 = (PrintTask2)ctx.getBean("printTask2");  
  26.                 printTask3.setName("Thread 3");  
  27.                 taskExecutor.execute(printTask3);  
  28.                   
  29.                 for(;;){  
  30.                         int count = taskExecutor.getActiveCount();  
  31.                         System.out.println("Active Threads : " + count);  
  32.                         try{  
  33.                                 Thread.sleep(1000);  
  34.                         }catch(InterruptedException e){  
  35.                                 e.printStackTrace();  
  36.                         }  
  37.                         if(count==0){  
  38.                                 taskExecutor.shutdown();  
  39.                                 break;  
  40.                         }  
  41.                 }  
  42.         }  
  43.   
  44. }  

 

输出:

 

Thread 1 is running.
Thread 2 is running.
Active Threads : 2
Thread 3 is running.
Active Threads : 3
Active Threads : 3
Active Threads : 3
Active Threads : 3
Thread 1 is running again.
Thread 2 is running again.
Thread 3 is running again.
Active Threads : 1
Active Threads : 0

从这三个简单的实例中,你是不是发现了Spring框架在多线程方面的强大之处!!

DRM全解析 —— encoder详解(3) 阅读详情

相关推荐

保姆级教程:用STM32CubeMX配置GD32的CAN总线(含异常处理)

本文提供了一份详细的STM32CubeMX配置GD32 CAN总线开发指南,涵盖从HAL库移植到异常处理的全过程。重点解析GD32与STM32在CAN总线初始化、报文发送优先级处理等方面的关键差异,并提供优化代码维护与版本控制的实用策略,帮助开发者高效完成项目迁移。

onion的博客 828

优雅地关闭线程池

由于在应用关闭的时候异步任务还在执行,导致类似数据库连接池这样的对象一并被销毁了,当异步任务中对数据库进行操作就会出错。 解决方案如下,重新设置线程池配置对象,新增线程池setWaitForTasksToCompleteOnShutdown()和setAwaitTerminationSeconds()配置: @Bean("taskExecutor") public...

a1058926697的博客 5257

STM32鱼塘水质监测系统设计与实现

物联网技术在农业领域的应用正逐步深入,其中传感器网络作为关键基础设施,通过实时数据采集与传输实现环境监测。基于STM32微控制器的嵌入式系统因其高性能和低功耗特性,成为物联网终端设备的理想选择。该系统通过DS18B20水温传感器、PH传感器和浊度传感器组成的多参数检测网络,配合4G通信模块实现水质数据的远程监控。在农业物联网场景中,这种解决方案不仅大幅降低了传统人工检测的成本,更能通过实时预警有效预防养殖损失。本文介绍的鱼塘水质监测系统正是这一技术的典型应用,展示了如何通过STM32和常见传感器构建高性价比

weixin_42173218的博客 620

SpringBoot | :异步开发之异步调用

前言 除了异步请求,一般上我们用的比较多的应该是异步调用。通常在开发过程中,会遇到一个方法是和实际业务无关的,没有紧密性的。比如记录日志信息等业务。这个时候正常就是启一个新线程去做一些业务处理,让主线程异步的执行其他业务。所以,本章节重点说下在SpringBoot中如何进行异步调用及其相关知识和注意点。 何为异步调用 说异步调用前,我们说说它对应的同步调用。通常开发过程中,一般上我们都是同步调用,...

weixin_34220179的博客 477

补洞与fairing算法

对网格进行补洞,remesh, 平滑,fairing, 最小二乘优化平滑

闪电彬彬的博客 1047

高通开发系列 - Camera之摄像头调试记录

记录一些调试内容

fulinux的博客 1216

解决springboot2.x 启用自动配置线程池后,线程池中无线程但是无法关闭程序的问题

//用来设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean taskExecutor.setWaitForTasksToCompleteOnShutdown(true); //该方法用来设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以确保应用最后能够被关闭,而不是阻塞住。 taskExecutor.setAwaitTerminationSeconds(60);...

zhaoweizw2000的博客 2859

SAP 联产品测试

最近领导一直要求研究一下SAP联产品的使用场景,之前只是自己摸索过一次,这个重新对联产品进行一个测试。 1、首先准备好物料主数据 注意主数据中需要勾选联产品标识。 设置好物料的分摊的百分比。 2、检查BOM 在BOM中也需要维护联产品的标识 只有当组件数量未负数时,才能勾选联产品的标识。如果组件数量正值,勾选联产品的标识时会报错。 3、我们创建生产订单 可以看到按正常的生产订单下达时,系统就报错了,问题点在于离散制造的生产订单基本是结算到物料的。但是联产品是按订单结算的, 所以需要对订单类型中的结算参

我小时候很黑的博客 2109

【Java基础干货】如何优雅关闭线程池实践总结

public void shutdown() { final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { // 检查权限 checkShutdownAccess(); // 设置线程池状态 advanceRunState(SHUTDOWN); // 中断空闲线程 interr...

在路上的德尔菲的博客 1689

[最新]MapReduce综合应用案例 — 气象数据清洗

【代码】[最新]MapReduce综合应用案例 — 气象数据清洗。

M_inherit的博客 1014

最全的Hermes安装教程以及Hermes WebUI安装部署和配置指南

* 直接执行命令**

小石头的专栏 1074

java 线程池 spring_Spring线程池开发实战及使用spring注解

本文提供了三个Spring多线程开发的例子,由浅入深,由于例子一目了然,所以并未做过多的解释。诸位一看便知。前提条件:1)在Eclipse创建一个Java项目,我取名为SpringThreadDemo。2)项目所需的JAR包如图所示: 下面开始。注:项目源码已经托管到GitHub,地址:https://github.com/chszs/SpringThreadDemo例子1:Spring结合Jav...

weixin_35327824的博客 516

SpringBoot系列之实现一个AI聊天助手

本文介绍了基于Spring Boot框架实现的AI聊天助手项目。该项目使用Spring Boot 3.2.3、Spring AI 1.0.0-M5等技术栈,集成DeepSeek-R1-Distill-Llama-8B模型实现智能对话功能。文章详细介绍了项目配置流程、运行方式和核心代码实现,包括ChatMessage模型类和服务类ChatService的关键功能,如消息处理、历史记录管理和AI响应获取等。读者可通过提供的GitHub链接获取完整代码,快速搭建自己的AI聊天应用。

Nicky's blog 1450
上一篇: 关于 Nginx+Tomcat+Memcached做负载均衡加共享session
下一篇: Spring中线程池的应用
danwind
博客等级 码龄19年 6粉丝 118原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值