Spring线程池开发实战
Spring线程池开发实战
作者:chszs,转载需注明。
作者博客主页:http://blog.csdn.net/chszs
本文提供了三个Spring多线程开发的例子,由浅入深,由于例子一目了然,所以并未做过多的解释。诸位一看便知。
前提条件:
1)在Eclipse创建一个Java项目,我取名为SpringThreadDemo。
2)项目所需的JAR包如图所示:
下面开始。
注:项目源码已经托管到GitHub,地址:https://github.com/chszs/SpringThreadDemo
例子1:Spring结合Java线程。
通过继承Thread创建一个简单的Java线程,然后使用@Component让Spring容器管理此线程,Bean的范围必须是prototype,因此每个请求都会返回一个新实例,运行每个单独的线程。
PrintThread.java
- package com.chszs.thread;
- import org.springframework.stereotype.Component;
- import org.springframework.context.annotation.Scope;
- @Component
- @Scope("prototype")
- public class PrintThread extends Thread{
- @Override
- public void run(){
- System.out.println(getName() + " is running.");
- try{
- Thread.sleep(5000);
- }catch(InterruptedException e){
- e.printStackTrace();
- }
- System.out.println(getName() + " is running again.");
- }
- }
AppConfig.java
- package com.chszs.config;
- import org.springframework.context.annotation.ComponentScan;
- import org.springframework.context.annotation.Configuration;
- @Configuration
- @ComponentScan(basePackages="com.chszs.thread")
- public class AppConfig {
- }
App.java
- package com.chszs;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.annotation.AnnotationConfigApplicationContext;
- import com.chszs.config.AppConfig;
- import com.chszs.thread.PrintThread;
- public class App {
- public static void main(String[] args){
- ApplicationContext ctx =
- new AnnotationConfigApplicationContext(AppConfig.class);
- PrintThread printThread1 = (PrintThread)ctx.getBean("printThread");
- printThread1.setName("Thread 1");
- PrintThread printThread2 = (PrintThread)ctx.getBean("printThread");
- printThread2.setName("Thread 2");
- PrintThread printThread3 = (PrintThread)ctx.getBean("printThread");
- printThread3.setName("Thread 3");
- PrintThread printThread4 = (PrintThread)ctx.getBean("printThread");
- printThread4.setName("Thread 4");
- PrintThread printThread5 = (PrintThread)ctx.getBean("printThread");
- printThread5.setName("Thread 5");
- printThread1.start();
- printThread2.start();
- printThread3.start();
- printThread4.start();
- printThread5.start();
- }
- }
输出:
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
- package com.chszs.thread;
- public class PrintTask implements Runnable{
- String name;
- public PrintTask(String name){
- this.name = name;
- }
- @Override
- public void run() {
- System.out.println(name + " is running.");
- try{
- Thread.sleep(5000);
- }catch(InterruptedException e){
- e.printStackTrace();
- }
- System.out.println(name + " is running again.");
- }
- }
Spring-Config.xml
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.1.xsd">
- <bean id="taskExecutor"
- class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
- <property name="corePoolSize" value="5" />
- <property name="maxPoolSize" value="10" />
- <property name="WaitForTasksToCompleteOnShutdown" value="true" />
- </bean>
- </beans>
注意这个Spring配置文件的位置,如图所示:
App1.java
- package com.chszs;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
- import com.chszs.thread.PrintTask;
- public class App1 {
- public static void main(String[] args) {
- ApplicationContext ctx =
- new ClassPathXmlApplicationContext("resources/Spring-Config.xml");
- ThreadPoolTaskExecutor taskExecutor =
- (ThreadPoolTaskExecutor)ctx.getBean("taskExecutor");
- taskExecutor.execute(new PrintTask("Thread 1"));
- taskExecutor.execute(new PrintTask("Thread 2"));
- taskExecutor.execute(new PrintTask("Thread 3"));
- taskExecutor.execute(new PrintTask("Thread 4"));
- taskExecutor.execute(new PrintTask("Thread 5"));
- // 检查活动的线程,如果活动线程数为0则关闭线程池
- for(;;){
- int count = taskExecutor.getActiveCount();
- System.out.println("Active Threads : " + count);
- try{
- Thread.sleep(1000);
- }catch(InterruptedException e){
- e.printStackTrace();
- }
- if(count==0){
- taskExecutor.shutdown();
- break;
- }
- }
- }
- }
输出:
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
- package com.chszs.thread;
- import org.springframework.context.annotation.Scope;
- import org.springframework.stereotype.Component;
- @Component
- @Scope("prototype")
- public class PrintTask2 implements Runnable {
- String name;
- public void setName(String name) {
- this.name = name;
- }
- @Override
- public void run(){
- System.out.println(name + " is running.");
- try{
- Thread.sleep(5000);
- }catch(InterruptedException e){
- e.printStackTrace();
- }
- System.out.println(name + " is running again.");
- }
- }
AppConfig.java
- package com.chszs.config;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.ComponentScan;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
- @Configuration
- @ComponentScan(basePackages="com.chszs.thread")
- public class AppConfig {
- @Bean
- public ThreadPoolTaskExecutor taskExecutor(){
- ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
- pool.setCorePoolSize(5);
- pool.setMaxPoolSize(10);
- pool.setWaitForTasksToCompleteOnShutdown(true);
- return pool;
- }
- }
App2.java
- package com.chszs;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.annotation.AnnotationConfigApplicationContext;
- import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
- import com.chszs.config.AppConfig;
- import com.chszs.thread.PrintTask2;
- public class App2 {
- public static void main(String[] args) {
- ApplicationContext ctx =
- new AnnotationConfigApplicationContext(AppConfig.class);
- ThreadPoolTaskExecutor taskExecutor =
- (ThreadPoolTaskExecutor)ctx.getBean("taskExecutor");
- PrintTask2 printTask1 = (PrintTask2)ctx.getBean("printTask2");
- printTask1.setName("Thread 1");
- taskExecutor.execute(printTask1);
- PrintTask2 printTask2 = (PrintTask2)ctx.getBean("printTask2");
- printTask2.setName("Thread 2");
- taskExecutor.execute(printTask2);
- PrintTask2 printTask3 = (PrintTask2)ctx.getBean("printTask2");
- printTask3.setName("Thread 3");
- taskExecutor.execute(printTask3);
- for(;;){
- int count = taskExecutor.getActiveCount();
- System.out.println("Active Threads : " + count);
- try{
- Thread.sleep(1000);
- }catch(InterruptedException e){
- e.printStackTrace();
- }
- if(count==0){
- taskExecutor.shutdown();
- break;
- }
- }
- }
- }
输出:
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框架在多线程方面的强大之处!!
Spring线程池开发实战的更多相关文章
- Spring线程池由浅入深的3个示例
作者博客主页:http://blog.csdn.net/chszs 本文提供了三个Spring多线程开发的例子,由浅入深,由于例子一目了然,所以并未做过多的解释.诸位一看便知. 前提条件: 1)在Ec ...
- Spring线程池配置模板设计(基于Springboot)
目录 线程池配置模板 基础的注解解释 常用配置参数 配置类设计 线程池使用 ThreadPoolTaskExecutor源码 线程池配置模板 springboot给我们提供了一个线程池的实现,它的底层 ...
- Spring线程池ThreadPoolTaskExecutor配置及详情
Spring线程池ThreadPoolTaskExecutor配置及详情 1. ThreadPoolTaskExecutor配置 <!-- spring thread pool executor ...
- 分享知识-快乐自己:Spring线程池配置
Spring通过ThreadPoolTaskExecutor实现线程池技术,它是使用jdk中的Java.util.concurrent.ThreadPoolExecutor进行实现. Spring 配 ...
- 【SSM Spring 线程池 OJ】 使用Spring线程池ThreadPoolTaskExecutor
最近做的Online Judge项目,在本地判题的实现过程中,遇到了一些问题,包括多线程,http通信等等.现在完整记录如下: OJ有一个业务是: 用户在前端敲好代码,按下提交按钮发送一个判题请求给后 ...
- spring线程池的同步和异步(1)
spring线程池(同步.异步) 一.spring异步线程池类图 二.简单介绍 2.1. TaskExecutor---Spring异步线程池的接口类,其实质是java.util.concurrent ...
- 007-多线程-JUC线程池-Spring线程池配置、池子如何配置参数
一.概述 Spring通过ThreadPoolTaskExecutor实现线程池技术,它是使用jdk中的Java.util.concurrent.ThreadPoolExecutor进行实现. 1.1 ...
- JDK线程池和Spring线程池的使用
JDK线程池和Spring线程池实例,异步调用,可以直接使用 (1)JDK线程池的使用,此处采用单例的方式提供,见示例: public class ThreadPoolUtil { private s ...
- java和spring 线程池总结
1. spring 的线程池 ThreadPoolTaskExecutor @Configuration public class ThreadPoolConfig { @Bean("thr ...
随机推荐
- Jquery中日期插件jquery.datepick的使用
jsp的代码: <%@ page language="java" contentType="text/html; charset=UTF-8" pageE ...
- 在mac安装numpy matplotlib scipy
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #000000; background-color: #fffff ...
- HTML中判断手机是否安装某APP,跳转或下载该应用
有些时候在做前端输出的时候,需要和app的做些对接工作.就是在手机浏览器中下载某app时,能判断该用户是否安装了该应用.如果安装了该应用,就直接打开该应用:如果没有安装该应用,就下载该应用.那么下面就 ...
- Yii2 基于RESTful api 坑 访问会把控制器名称变为复数
'urlManager' => [ 'class' => 'yii\web\UrlManager', 'enablePrettyUrl' => true, 'enableStrict ...
- Spring Boot 系列教程18-itext导出pdf下载
Java操作pdf框架 iText是一个能够快速产生PDF文件的java类库.iText的java类对于那些要产生包含文本,表格,图形的只读文档是很有用的.它的类库尤其与java Servlet有很好 ...
- MongoDB本地安装与启用(windows )
MongoDB的安装与MongoDB服务配置 Mongo DB 是目前在IT行业非常流行的一种非关系型数据库(NoSql),其灵活的数据存储方式备受当前IT从业人员的青睐.Mongo DB很好的实现了 ...
- mysql count max min 语句用法
count 用法 求总条数 $sql="select count(*) as total from e_user"; $query = mysql_query($sql, $lin ...
- css的三种引入方式、常用的元素选择器以及css三大特性
第一.html文件中如何使用css html文件中使用css有3种方式:链接式.嵌入式.行内式,推荐使用程度依次递减:1.链接式:在html文件通过<link />标签引入,rel属性值必 ...
- 使用PowerDesigner创建mysql数据库表图
使用PowerDesigner 建数据库表. 一直很忙,没有时间写东西.这次搞点会声会色的,嘿嘿 此技能为项目经理必备技能. 本次主角: 1.在workspace下建立一项目: physical da ...
- centsOS下安装vsftp的配置
1. 添加用户组 # groupadd www 2. 修改配置 # vi /etc/vsftpd/vsftpd.conf 查找: #chroot_list_enable=YES #chroot_lis ...