spring的多线程配置

本文介绍了如何在Spring框架中配置和使用多线程。通过查看executor.xml的配置,我们可以了解到具体的线程池设置,这有助于提高应用程序的并发性能。在实际运行中,这些配置将影响到日志打印的输出和线程调度策略。

API:

Method Summary
 voidafterPropertiesSet()
          Calls initialize() after the container applied all property values.
protected  edu.emory.mathcs.backport.java.util.concurrent.BlockingQueuecreateQueue(int queueCapacity)
          Create the BlockingQueue to use for the ThreadPoolExecutor.
 voiddestroy()
          Calls shutdown when the BeanFactory destroys the task executor instance.
 voidexecute(Runnable task)
          Implementation of both the JSR-166 backport Executor interface and the Spring TaskExecutor interface, delegating to the ThreadPoolExecutor instance.
 voidexecute(Runnable task, long startTimeout)
          Execute the given task.
 intgetActiveCount()
          Return the number of currently active threads.
 intgetCorePoolSize()
          Return the ThreadPoolExecutor's core pool size.
 intgetKeepAliveSeconds()
          Return the ThreadPoolExecutor's keep-alive seconds.
 intgetMaxPoolSize()
          Return the ThreadPoolExecutor's maximum pool size.
 intgetPoolSize()
          Return the current pool size.
 edu.emory.mathcs.backport.java.util.concurrent.ThreadPoolExecutorgetThreadPoolExecutor()
          Return the underlying ThreadPoolExecutor for native access.
 voidinitialize()
          Creates the BlockingQueue and the ThreadPoolExecutor.
 booleanprefersShortLivedTasks()
          This task executor prefers short-lived work units.
 voidsetAllowCoreThreadTimeOut(boolean allowCoreThreadTimeOut)
          Specify whether to allow core threads to time out.
 voidsetBeanName(String name)
          Set the name of the bean in the bean factory that created this bean.
 voidsetCorePoolSize(int corePoolSize)
          Set the ThreadPoolExecutor's core pool size.
 voidsetKeepAliveSeconds(int keepAliveSeconds)
          Set the ThreadPoolExecutor's keep-alive seconds.
 voidsetMaxPoolSize(int maxPoolSize)
          Set the ThreadPoolExecutor's maximum pool size.
 voidsetQueueCapacity(int queueCapacity)
          Set the capacity for the ThreadPoolExecutor's BlockingQueue.
 voidsetRejectedExecutionHandler(edu.emory.mathcs.backport.java.util.concurrent.RejectedExecutionHandler rejectedExecutionHandler)
          Set the RejectedExecutionHandler to use for the ThreadPoolExecutor.
 voidsetThreadFactory(edu.emory.mathcs.backport.java.util.concurrent.ThreadFactory threadFactory)
          Set the ThreadFactory to use for the ThreadPoolExecutor's thread pool.
 voidsetThreadNamePrefix(String threadNamePrefix)
          Specify the prefix to use for the names of newly created threads.
 voidsetWaitForTasksToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown)
          Set whether to wait for scheduled tasks to complete on shutdown.
 voidshutdown()
          Perform a shutdown on the ThreadPoolExecutor.
<T> Future<T>
submit(Callable<T> task)
          Submit a Callable task for execution, receiving a Future representing that task.
 Future<?>submit(Runnable task)
          Submit a Runnable task for execution, receiving a Future representing that task.

executor.xml的配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:task="http://www.springframework.org/schema/task" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:jee="http://www.springframework.org/schema/jee"
	xsi:schemaLocation="http://www.springframework.org/schema/beans   
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
       http://www.springframework.org/schema/tx   
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd    
       http://www.springframework.org/schema/aop   
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd    
       http://www.springframework.org/schema/context   
       http://www.springframework.org/schema/context/spring-context-3.0.xsd  
       http://www.springframework.org/schema/task  
       http://www.springframework.org/schema/task/spring-task-3.0.xsd  
       http://www.springframework.org/schema/jee       
       http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">

	<!-- 如上添加 相关task标签 /|\ -->


	<!-- <dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-context-support</artifactId>
		<version>4.3.10.RELEASE</version>
	</dependency> -->

	<!-- spring线程池 -->
	<bean id="taskExecutor"
		class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
		<!-- 线程池维护线程的最少数量 -->
		<property name="corePoolSize" value="5" />
		<!-- 线程池维护线程所允许的空闲时间,默认为60s -->
		<property name="keepAliveSeconds" value="200" />
		<!-- 线程池维护线程的最大数量 -->
		<property name="maxPoolSize" value="20" />
		<!-- 缓存队列最大长度 -->
		<property name="queueCapacity" value="20" />
		<!-- 对拒绝task的处理策略 线程池对拒绝任务(无线程可用)的处理策略,目前只支持AbortPolicy、CallerRunsPolicy;默认为后者 -->
		<property name="rejectedExecutionHandler">
			<!-- AbortPolicy:直接抛出java.util.concurrent.RejectedExecutionException异常 -->
			<!-- CallerRunsPolicy:主线程直接执行该任务,执行完之后尝试添加下一个任务到线程池中,可以有效降低向线程池内添加任务的速度 -->
			<!-- DiscardOldestPolicy:抛弃旧的任务、暂不支持;会导致被丢弃的任务无法再次被执行 -->
			<!-- DiscardPolicy:抛弃当前任务、暂不支持;会导致被丢弃的任务无法再次被执行 -->
			<bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
		</property>
		<property name="waitForTasksToCompleteOnShutdown" value="true" />
	</bean>

</beans>

测试类ExecutorTest1.java的代码:
package com.soecode.lyf.web.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

public class ExecutorTest1 {


	@Test
	public void test() {

		try {

			ApplicationContext context1  = new ClassPathXmlApplicationContext("executor.xml"); 
			ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor)context1.getBean("taskExecutor");
			for(int i=0;i<10;i++){
				taskExecutor.execute(new Runnable(){
					@Override
					public void run() {
						System.out.println(Thread.currentThread());
					}
				});
			}
			System.out.println("main方法结束");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

打印的日志:

[org.springframework.context.support.ClassPathXmlApplicationContext] - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@55816088: startup date [Thu Feb 08 15:16:54 CST 2018]; root of context hierarchy
  [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from class path resource [executor.xml]
  [org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor] - Initializing ExecutorService  'taskExecutor'
  Thread[taskExecutor-1,5,main]
Thread[taskExecutor-3,5,main]
Thread[taskExecutor-4,5,main]
Thread[taskExecutor-2,5,main]
main方法结束
Thread[taskExecutor-1,5,main]
Thread[taskExecutor-1,5,main]
Thread[taskExecutor-1,5,main]
Thread[taskExecutor-1,5,main]
Thread[taskExecutor-2,5,main]
Thread[taskExecutor-5,5,main]


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值