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框架在多线程方面的强大之处!!

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

Spring线程池开发实战相关推荐

  1. spring 线程池_Spring线程池服务

    spring 线程池 线程池对于执行同步和异步过程非常重要. 本文介绍如何使用Spring开发和监视线程池服务. 创建线程池已通过两种替代方法进行了说明. 二手技术 : JDK 1.6.0_21 春天 ...

  2. C++强化之路之线程池开发整体框架(二)

    一.线程池开发框架 我所开发的线程池由以下几部分组成:  1.工作中的线程.也就是线程池中的线程,主要是执行分发来的task.  2.管理线程池的监督线程.这个线程的创建独立于线程池的创建,按照既定的 ...

  3. spring线程池的理解和使用

    1.spring线程池 <bean id="taskExecutor" class="org.springframework.scheduling.concurre ...

  4. Spring线程池服务

    线程池对于执行同步和异步过程非常重要. 本文介绍如何使用Spring开发和监视线程池服务. 创建线程池已通过两种替代方法进行了说明. 二手技术 : JDK 1.6.0_21 Spring3.0.5 M ...

  5. spring线程池的使用

    为了尽量减少耗时操作对Action执行的影响,使用TaskExecutor线程池来管理耗时任务,作为后台进程执行,从而解决了问题. 场景:     使用了Struts和Spring,但Struts的A ...

  6. spring线程池使用

    为何使用多线程 对于复杂的业务逻辑下,有时候需要使用多线程执行,以优化项目的执行速度 单线程同步执行的场景中,如果前边出现异常,会导致所有任务中断,异步执行没有这样的问题 多线程实现方式:线程池 减少 ...

  7. Spring 线程池使用

    Spring 中默认自带线程池_org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor,一般有可以直接使用,这是时候使用的是默 ...

  8. Spring线程池异步传递MDC信息

    目录 1. 什么是MDC 2. 引入MDC打印步骤 2.1 pom依赖 2.2 log4j2打印日志配置文件 3 步骤演示 3.1 单线程业务使用示例 postman查询示例 查询代码 查询日志 3. ...

  9. Android 自定义线程池的实战

    前言:在上一篇文章中我们讲到了AsyncTask的基本使用.AsyncTask的封装.AsyncTask 的串行/并行线程队列.自定义线程池.线程池的快速创建方式. 对线程池不了解的同学可以先看 An ...

最新文章

  1. JS实现表格列宽拖动
  2. applet打包的MANIFEST.MF配置
  3. linux挂载盘符扫描,Linux下挂载ISCSI的盘符问题
  4. ssh远程登录执行shell脚本,找不到jps
  5. netcat使用方法_记一次NC(NETCAT)传输文件实战
  6. django 1.8 官方文档翻译:6-5-1 Django中的测试
  7. 【平头哥蓝牙Mesh网关开发套件试用体验】蓝牙mesh网关接入网络
  8. Github 资源收集
  9. 用html做祝福语朋友,对朋友的励志祝福语大全
  10. 软件工程复试面试问题总结(二)
  11. 利用脚本一键删除微博
  12. 《场景革命》读书笔记
  13. 【转】新世纪研究生公共英语教材阅读A 答案
  14. mysql duplicated错误码_Mysql常见错误码讲解
  15. E_Groundhog Chasing Death(不错的数论)
  16. KONG (API网关) 用CORS处理跨域,针对:非简单请求
  17. KK 给年轻人的99条建议
  18. 11、IOC 之使用 JSR 330 标准注释
  19. 用计算机程序实现离散化的对象模型,模糊PID应用
  20. HDU 4262 Juggler 树状数组

热门文章

  1. Spring 框架教程
  2. 观察者模式,从公众号群发说起
  3. vue data变量之间相互赋值或进行数据联动
  4. 【C语言】输入一个字符串,并对字符串中的偶数位置的字符按从小到大的顺序排序,奇数位置的字符不动,输出排序后的结果...
  5. Weblogic11g安装部署-winserver篇
  6. Getting started with Bitcoin
  7. 了解Stack Overflow,这是您获得编程和调试知识的途径
  8. gitter 卸载_最佳Gitter渠道:游戏开发人员
  9. springMVC导入excel案例poi
  10. Node版本管理nvm的用法