ThreadPoolTaskExecutor 使用和原理

使用

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:执行了...0
taskExecutor-2:执行了...1
taskExecutor-3:执行了...2
taskExecutor-4:执行了...3
taskExecutor-5:执行了...4
main process is finish .....
taskExecutor-1:执行了...5
taskExecutor-3:执行了...7
taskExecutor-4:执行了...8
taskExecutor-2:执行了...6
taskExecutor-5:执行了...9
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值