`

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
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics