`

Spring线程池结合Spring托管线程类

阅读更多

Spring线程池结合Spring托管线程Bean

@Component 注释声明Spring的托管Bean

@Scope("prototype")  注释说明为“多例”

 

package com.test.thread;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
public class PrintTask 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.");
        }
}

 

package com.test.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
// 表示所扫描所包含的@Bean
@ComponentScan(basePackages="com.test.thread")
public class AppConfig {
        @Bean
        public ThreadPoolTaskExecutor taskExecutor(){
                ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
                pool.setCorePoolSize(5); //线程池活跃的线程数
                pool.setMaxPoolSize(10); //线程池最大活跃的线程数 
                pool.setQueueCapacity(25); // 队列的最大容量 
                pool.setWaitForTasksToCompleteOnShutdown(true);
                return pool;
        }
}

 

package com.test;

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.PrintTask;

public class App {
        public static void main(String[] args) {
                ApplicationContext ctx = 
            new AnnotationConfigApplicationContext(AppConfig.class);
                ThreadPoolTaskExecutor taskExecutor =
            (ThreadPoolTaskExecutor)ctx.getBean("taskExecutor");
                
                PrintTask2 printTask1 = (PrintTask2)ctx.getBean("printTask");
                printTask1.setName("Thread 1");
                taskExecutor.execute(printTask1);
                
                PrintTask2 printTask2 = (PrintTask2)ctx.getBean("printTask");
                printTask2.setName("Thread 2");
                taskExecutor.execute(printTask2);
                
                PrintTask2 printTask3 = (PrintTask2)ctx.getBean("printTask");
                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;
                        }
                }
        }

}

 备注:如PrintTask类中有操作dao,service中的数据库@Autowired找不到类,那就要注意@ComponentScan(basePackages="com.test.thread")是否有问题了~应包含全部@Bean包的最底级别。

Spring线程池结合非Spring托管Bean。

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>

 

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;
                        }
                }
        }

}

Spring结合Java线程

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

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.");
        }
}

 

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();
        }
}

 

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 {
}

 锁依赖的jar

org.springframework.aop-3.1.3.RELEASE.jar
org.springframework.asm-3.1.3.RELEASE.jar
org.springframework.beans-3.1.3.RELEASE.jar
org.springframework.context-3.1.3.RELEASE.jar
org.springframework.core-3.1.3.RELEASE.jar
org.springframework.expression-3.1.3.RELEASE.jar
commons-logging.jar
aopalliance-1.0.jar
asm-3.3.1.jar
cglib-2.2.2.jar

另外附上线程池属性,作用等你发掘,欢迎拍砖~

protected edu.emory.mathcs.backport.java.util.concurrent.BlockingQueue createQueue(int queueCapacity)
//Create the BlockingQueue to use for the ThreadPoolExecutor.
 void	destroy()
//Calls shutdown when the BeanFactory destroys the task executor instance.
 void	execute(Runnable task)
//Implementation of both the JSR-166 backport Executor interface and the Spring 
TaskExecutor interface, delegating to the ThreadPoolExecutor instance.
 int	getActiveCount()
//Return the number of currently active threads.
 int	getCorePoolSize()
//Return the ThreadPoolExecutor's core pool size.
 int	getKeepAliveSeconds()
//Return the ThreadPoolExecutor's keep-alive seconds.
 int	getMaxPoolSize()
//Return the ThreadPoolExecutor's maximum pool size.
 int	getPoolSize()
//Return the current pool size.
 edu.emory.mathcs.backport.java.util.concurrent.ThreadPoolExecutor	getThreadPoolExecutor()
//Return the underlying ThreadPoolExecutor for native access.
 void	initialize()
//Creates the BlockingQueue and the ThreadPoolExecutor.
 boolean	prefersShortLivedTasks()
//This task executor prefers short-lived work units.
 void	setAllowCoreThreadTimeOut(boolean allowCoreThreadTimeOut)
//Specify whether to allow core threads to time out.
 void	setBeanName(String name)
//Set the name of the bean in the bean factory that created this bean.
 void	setCorePoolSize(int corePoolSize)
//Set the ThreadPoolExecutor's core pool size.
 void	setKeepAliveSeconds(int keepAliveSeconds)
//Set the ThreadPoolExecutor's keep-alive seconds.
 void	setMaxPoolSize(int maxPoolSize)
//Set the ThreadPoolExecutor's maximum pool size.
 void	setQueueCapacity(int queueCapacity)
//Set the capacity for the ThreadPoolExecutor's BlockingQueue.
 void	setRejectedExecutionHandler(edu.emory.mathcs.backport.java.util.concurrent.RejectedExecutionHandler rejectedExecutionHandler)
//Set the RejectedExecutionHandler to use for the ThreadPoolExecutor.
 void	setThreadFactory(edu.emory.mathcs.backport.java.util.concurrent.ThreadFactory threadFactory)
//Set the ThreadFactory to use for the ThreadPoolExecutor's thread pool.
 void	setThreadNamePrefix(String threadNamePrefix)
//Specify the prefix to use for the names of newly created threads.
 void	setWaitForTasksToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown)
//Set whether to wait for scheduled tasks to complete on shutdown.
 void	shutdown()
//Perform a shutdown on the ThreadPoolExecutor.
 

 

 

 

0
2
分享到:
评论

相关推荐

    mybatis-spring-1.3.3.jar官方下载

    它负责配置 MyBatis 的配置文件、环境信息、数据源等,并为 Spring 容器提供一个可以托管的 SqlSessionFactory 实例。 3. **MapperScannerConfigurer**:这个类用于扫描指定包下的 Mapper 接口,并自动将其注册到 ...

    获取Spring容器

    例如,在非Spring托管的代码或者需要动态获取Bean的情况下。下面详细介绍如何通过编程的方式手动获取Spring容器中的Bean。 ##### 1. 配置自定义ApplicationContext 首先,在`spring-context.xml`中添加一个名为`...

    spring rmi应用

    这个类通常会托管在服务器JVM上,并通过RMI注册表暴露给客户端。 3. **配置Spring容器**:在Spring的XML配置文件中,你需要声明一个`&lt;bean&gt;`来表示远程服务,使用`&lt;rmi:export&gt;`或`&lt;bean class="org.spring...

    spring+hibernate+struts企业面试题(精华)

    6. **Struts2与Spring整合**:结合Spring进行依赖注入,提高组件的可测试性。 在面试中,可能会遇到的问题包括但不限于如何解决多线程下的Session问题、AOP的应用场景、Struts2的拦截器链、Hibernate的性能优化策略...

    SSH整合中 hibernate托管给Spring得到SessionFactory

    标题“SSH整合中 hibernate托管给Spring得到SessionFactory”和描述“Spring文件中的 SessionFactory中 加入为了能得到...同时,也展示了不使用Spring托管的情况下,Hibernate如何通过配置文件独立管理SessionFactory。

    SSH+JBoss+多线程的电子宠物系统

    SSH+JBoss+多线程的电子宠物系统是一种基于Java技术栈开发的复杂应用程序,它融合了Spring、Struts和Hibernate三大主流框架的优势,利用JBoss应用服务器提供服务,并通过多线程技术来实现高性能和高并发处理。...

    Java Web大作业(Spring Boot + Vue).zip

    【Java Web大作业(Spring Boot + Vue)】项目是一个典型的现代Web开发实例,结合了Java后端框架Spring Boot和前端JavaScript框架Vue.js。这个项目旨在帮助大学生深入理解Java Web开发,通过实际操作来巩固和应用所...

    mybatise jar

    MyBatis-Spring 是一个 MyBatis 和 Spring 的集成库,它为 MyBatis 的 SqlSessionFactory 和 SqlSession 提供了 Spring 的托管功能。通过这个集成,我们可以将 MyBatis 的数据访问层无缝地融入到 Spring 的 IoC 容器...

    JavaCodeTeaching:托管Java和Spring的Java代码教学

    6. **多线程**:理解线程的基本概念,如何创建和管理线程,同步机制如synchronized关键字和Lock接口。 7. **网络编程**:学习套接字编程,理解TCP和UDP协议,以及HTTP协议的基础知识。 8. **反射与注解**:了解...

    tomcat 7.0

    Tomcat 7.0.61作为Web服务器,为这些应用程序提供运行环境,使得Spring MVC应用程序能够被正确地托管和执行。 【详细知识点】 1. **Tomcat 7.0特性**:Tomcat 7引入了一些重要的新特性,包括支持Servlet 3.0规范、...

    mybatis中文版教程

    - **注入映射器**:通过`MapperFactoryBean`可以轻松地将数据映射器接口注入到任何Spring托管的Bean中。 - **自动配置**:对于某些情况,可以通过配置`MapperScannerConfigurer`来自动扫描和注册映射器接口。 #### ...

    阿里巴巴开源在线分析诊断工具Arthas(阿尔萨斯)

    - `thread`:查看线程信息,包括当前线程堆栈、死锁检测等。 - `jvm`:查看JVM相关信息,如内存、垃圾回收、线程池状态等。 #### 1.2 Spring Boot应用支持 Arthas特别优化了对Spring Boot应用的支持,可以快速定位...

    java面试,Java基础知识

    - **线程池**:线程池是管理一组线程的有效方式,有助于减少线程创建和销毁的成本。常见的线程池有FixedThreadPool、CachedThreadPool、ScheduledThreadPoolExecutor等。 #### 2. 基本算法与数据结构 - **排序算法*...

    ssh+cxf整合及单个cxf测试样例

    Spring可以管理Hibernate的SessionFactory,确保在多线程环境下的线程安全。 接下来,我们来谈谈CXF的测试。CXF提供了丰富的测试工具和API,可以方便地对服务进行单元测试和集成测试。例如,我们可以使用`...

    MyBatis培训课件

    2. **通过 Spring 托管创建 SqlSessionFactory**:在基于 Spring 的项目中,通常会采用这种方式来创建 SqlSessionFactory。这种方式的好处是可以利用 Spring 的依赖注入特性,减少手动配置的工作量。 - 在 Spring ...

    tomcat输出输出着就不输出了,什么原因?解决方法是

    4. **Spring生命周期管理**:你提到将方法托管给Spring后问题解决,这可能是因为Spring管理了bean的生命周期,确保了其持久性。在Spring中,你可以通过`@Scope("prototype")`来创建多实例,避免单例bean被容器误认为...

    Hibernate_DEV_GUIDE

    SessionFactory是线程安全的工厂类,用于创建Session;Session是与数据库交互的主要接口,负责对象的持久化操作;Transaction则管理数据库事务;Query和Criteria API则提供了强大的查询功能。 3. **配置 Hibernate*...

    java面试问题汇总(非常全面)

    - `Thread` 类:Java 提供的基础线程类。 - `Runnable` 接口:实现该接口可以创建线程任务。 - `Callable` 接口:与 `Runnable` 类似,但可以返回结果并抛出异常。 - `Future` 和 `FutureTask`:用于获取异步计算的...

    《IT学习资料》-java后端学习笔记.zip

    5. **Java多线程**:这部分内容可能涉及Java并发编程,包括线程的创建、同步、锁机制、并发工具类等,这些都是构建高性能、高并发应用的关键知识。 6. **Java基础**:这部分可能涵盖了Java语言的基本语法、数据类型...

Global site tag (gtag.js) - Google Analytics