ThreadPoolTaskExecutor 使用和原理

使用

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

pom.xml


org.springframework
spring-context-support
3.0.5.RELEASE

applicationContext.xml



<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" >
        
        
        
        
        <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

你可能感兴趣的:(服务器开发)