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新聞熱點
疑難解答