<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> <!-- 异步线程池 --> <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> <!-- 核心线程数 --> <property name="corePoolSize" value="8" /> <!-- 最大线程数 --> <property name="maxPoolSize" value="100" /> <!-- 队列最大长度 >=mainExecutor.maxSize --> <property name="queueCapacity" value="0" /> <!-- 线程池维护线程所允许的空闲时间 --> <property name="keepAliveSeconds" value="500" /> <!-- 线程池对拒绝任务(无线程可用)的处理策略 --> <property name="rejectedExecutionHandler"> <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" /> </property> </bean> </beans>
public class MyCallable implements Callable<String> { private String name; public MyCallable(String name){ this.name=name; } @Override public String call() throws Exception { Thread.sleep(5000); return name; } }
import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; public class threadPoolTest { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) ctx.getBean("taskExecutor"); CompletionService<String> cs = new ExecutorCompletionService<>(taskExecutor); for (int i = 0; i < 5; i++) { cs.submit(new MyCallable("Thread "+i)); } for (int i = 0; i < 5; i++){ try { System.out.println(cs.take().get()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext1.xml"); ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) ctx.getBean("taskExecutor"); List<Future<String>> list = new ArrayList<Future<String>>(); for (int i = 0; i < 5; i++) { Future<String> future= taskExecutor.submit(new MyCallable("Thread "+i)); list.add(future); } for (Iterator iterator = list.iterator(); iterator.hasNext();) { Future<String> future = (Future<String>) iterator.next(); try { System.out.println(future.get()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } iterator.remove(); } System.out.println(list.size()); }
queueCapacity参数是0的话,用的是SynchronousQueue,否则是LinkedBlockingQueue。
用CallerRunsPolicy策略的话,线程超过最大数量和队列长度之和,主线程等待,直到线程池有空闲线程。