首页 > 学院 > 开发设计 > 正文

ThreadPoolTaskExecutor 使用和原理

2019-11-10 17:20:55
字体:
来源:转载
供稿:网友

使用

ThreadPoolTaskExecutor是一个sPRing的线程池技术,利用他可以轻松的视线线程池,下面代码是具体的使用

pom.xml <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>3.0.5.RELEASE</version> </dependency>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "/spring-beans.dtd"><beans><bean id ="taskExecutor" class ="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor" > <property name ="corePoolSize" value ="5" /> <!--核心线程数 --> <property name ="keepAliveSeconds" value ="3000" /> <!-- 某线程空闲超过这个时间,就回收该线程 --> <property name ="maxPoolSize" value ="10" /> <!--最大线程数 --> <property name ="queueCapacity" value ="1000" /> <!-- 队列大小 --> <property name= "rejectedExecutionHandler" > <!-- AbortPolicy:直接抛出java.util.concurrent.RejectedExecutionException异常 --> <!-- CallerRunsPolicy:主线程直接执行该任务,执行完之后尝试添加下一个任务到线程池中,可以有效降低向线程池内添加任务的速度 --> <!-- DiscardOldestPolicy:抛弃旧的任务、暂不支持;会导致被丢弃的任务无法再次被执行 --> <!-- DiscardPolicy:抛弃当前任务、暂不支持;会导致被丢弃的任务无法再次被执行 --> <bean class = "java.util.concurrent.ThreadPoolExecutor$DiscardPolicy" /> </property></bean></beans>

SpringThread.java

public class SpringThread extends Thread{ private int parameter; public SpringThread(int parameter){ this.parameter = parameter; } @Override public void run() { System.out.println(Thread.currentThread().getName() + ":执行了..." + parameter); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } }}

测试代码

import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.core.task.TaskExecutor;public class App{ public static void main( String[] args ) { //System.out.println( "Hello World!" ); ApplicationContext appContext = new ClassPathXmlApplicationContext("file:applicationContext.xml"); TaskExecutor executor = (TaskExecutor) appContext.getBean("taskExecutor"); for (int i = 0; i < 10; i++) { SpringThread t = new SpringThread(i); executor.execute(t); } System.out.println("main process is finish ....."); }}

运行结果:

taskExecutor-1:执行了...0taskExecutor-2:执行了...1taskExecutor-3:执行了...2taskExecutor-4:执行了...3taskExecutor-5:执行了...4main process is finish .....taskExecutor-1:执行了...5taskExecutor-3:执行了...7taskExecutor-4:执行了...8taskExecutor-2:执行了...6taskExecutor-5:执行了...9
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表