您目前处于:笔记
2014-01-11
|
1. ThreadPoolExecutor Spring 中的 ThreadPoolTaskExecutor 是借助于 JDK 并发包中的 java.util.concurrent.ThreadPoolExecutor 来实现的,下面先学习下 ThreadPoolExecutor 中的相关信息,ThreadPoolExecutor 构造函数如下: public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { } 参数具体意义: int corePoolSize:线程池维护线程的最小数量 ThreadPoolExecutor 源码分析: public class ThreadPoolExecutor extends AbstractExecutorService { …… } public abstract class AbstractExecutorService implements ExecutorService { …… } public interface ExecutorService extends Executor { …… } 2. Spring 中 ThreadPoolTaskExecutor 直接调用 ThreadPoolTaskExecutor poolTaskExecutor = new ThreadPoolTaskExecutor(); //线程池所使用的缓冲队列 poolTaskExecutor.setQueueCapacity(200); //线程池维护线程的最少数量 poolTaskExecutor.setCorePoolSize(5); //线程池维护线程的最大数量 poolTaskExecutor.setMaxPoolSize(1000); //线程池维护线程所允许的空闲时间 poolTaskExecutor.setKeepAliveSeconds(30000); poolTaskExecutor.initialize(); Spring配置文件 <!-- 配置Spring线程池 --> <bean id="threadPoolTaskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> <property name="corePoolSize" value="30"/> <property name="maxPoolSize" value="200"/> <property name="keepAliveSeconds" value="5"/> <property name="queueCapacity" value="1000"/> <property name="rejectedExecutionHandler"> <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy"/> </property> </bean> ThreadPoolTaskExecutor 执行器的处理流程: (1) 当线程池大小小于 corePoolSize 就新建线程,并处理请求 ThreadPoolTaskExecutor 源码分析: public class ThreadPoolTaskExecutor extends CustomizableThreadFactory implements SchedulingTaskExecutor, Executor, BeanNameAware, InitializingBean, DisposableBean { …… } Spring的 ThreadPoolTaskExecutor 类最终是通过调用 Java 的 ThreadPoolExecutor 的 void execute(Runnable task) 方法或 Future submit(Runnable task) 方法执行任务的。 public class ThreadPoolTaskExecutor extends CustomizableThreadFactory implements SchedulingTaskExecutor, Executor, BeanNameAware, InitializingBean, DisposableBean { private ThreadPoolExecutor threadPoolExecutor; …… public void execute(Runnable task) { Executor executor = getThreadPoolExecutor(); try { executor.execute(task); } catch (RejectedExecutionException ex) { throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, ex); } } public ThreadPoolExecutor getThreadPoolExecutor() throws IllegalStateException { Assert.state(this.threadPoolExecutor != null, "ThreadPoolTaskExecutor not initialized"); return this.threadPoolExecutor; } } 转载请并标注: “本文转载自 linkedkeeper.com ” ©著作权归作者所有 |