Spring线程池开发实战

简介: 本文提供了三个Spring多线程开发的例子,由浅入深,由于例子一目了然,所以并未做过多的解释。诸位一看便知。 前提条件: 1)在Eclipse创建一个Java项目,我取名为SpringThreadDemo。
本文提供了三个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 print ?
  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 print ?
  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 print ?
  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 print ?
  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 print ?
  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 print ?
  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.csdn.net/chszs

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


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


PrintTask2.java


[java]   view plain copy print ?
  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 print ?
  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 print ?
  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框架在多线程方面的强大之处!!

目录
相关文章
|
1天前
|
Java 应用服务中间件 测试技术
深入探索Spring Boot Web应用源码及实战应用
【5月更文挑战第11天】本文将详细解析Spring Boot Web应用的源码架构,并通过一个实际案例,展示如何构建一个基于Spring Boot的Web应用。本文旨在帮助读者更好地理解Spring Boot的内部工作机制,以及如何利用这些机制优化自己的Web应用开发。
20 3
|
1天前
|
安全 Java 开发者
深入理解Spring Boot配置绑定及其实战应用
【4月更文挑战第10天】本文详细探讨了Spring Boot中配置绑定的核心概念,并结合实战示例,展示了如何在项目中有效地使用这些技术来管理和绑定配置属性。
13 1
|
1天前
|
安全 Java 测试技术
Spring Boot集成支付宝支付:概念与实战
【4月更文挑战第29天】在电子商务和在线业务应用中,集成有效且安全的支付解决方案是至关重要的。支付宝作为中国领先的支付服务提供商,其支付功能的集成可以显著提升用户体验。本篇博客将详细介绍如何在Spring Boot应用中集成支付宝支付功能,并提供一个实战示例。
37 2
|
1天前
|
Java 关系型数据库 数据库
Spring Boot多数据源及事务管理:概念与实战
【4月更文挑战第29天】在复杂的企业级应用中,经常需要访问和管理多个数据源。Spring Boot通过灵活的配置和强大的框架支持,可以轻松实现多数据源的整合及事务管理。本篇博客将探讨如何在Spring Boot中配置多数据源,并详细介绍事务管理的策略和实践。
38 3
|
1天前
|
安全 Java Spring
Spring框架中的单例Bean是线程安全的吗?
Spring框架中的单例Bean是线程安全的吗?
10 1
|
1天前
|
开发框架 监控 Java
深入探索Spring Boot的监控、管理和测试功能及实战应用
【5月更文挑战第14天】Spring Boot是一个快速开发框架,提供了一系列的功能模块,包括监控、管理和测试等。本文将深入探讨Spring Boot中监控、管理和测试功能的原理与应用,并提供实际应用场景的示例。
14 2
|
1天前
|
监控 Java Spring
Spring Boot中一般如何使用线程池?
在Spring Boot应用程序中,合理地使用线程池可以有效地提高系统的性能和并发处理能力。本文将深入探讨Spring Boot中如何一般性地使用线程池,包括线程池的配置、使用方式以及一些最佳实践。
22 0
|
1天前
|
Java Spring 容器
深入理解Spring Boot启动流程及其实战应用
【5月更文挑战第9天】本文详细解析了Spring Boot启动流程的概念和关键步骤,并结合实战示例,展示了如何在实际开发中运用这些知识。
17 2
|
1天前
|
前端开发 安全 Java
使用Spring框架加速Java开发
使用Spring框架加速Java开发
56 0
|
1天前
|
JavaScript Java 开发者
Spring Boot中的@Lazy注解:概念及实战应用
【4月更文挑战第7天】在Spring Framework中,@Lazy注解是一个非常有用的特性,它允许开发者控制Spring容器的bean初始化时机。本文将详细介绍@Lazy注解的概念,并通过一个实际的例子展示如何在Spring Boot应用中使用它。
21 2