StandardThreadExecutor类
该类实现了Executor接口,Executor表示可以在Tomcat组件之间共享的线程池,在之前是每个连接器有一个线程池。这样就可以由多个组件之间共享。
- <Connector
- port="8009"
- protocol="AJP/1.3"
- maxThreads="5000"
- executor="tomcatThreadPool"
该类的start方法
public void start() throws LifecycleException {
lifecycle.fireLifecycleEvent(BEFORE_START_EVENT, null);
TaskQueue taskqueue = new TaskQueue();//内部类,继承LinkedBlockingQueue
TaskThreadFactory tf = new TaskThreadFactory(namePrefix);//内部类,实现ThreadFactory
lifecycle.fireLifecycleEvent(START_EVENT, null);
executor = new ThreadPoolExecutor(getMinSpareThreads(), getMaxThreads(), maxIdleTime, TimeUnit.MILLISECONDS,taskqueue, tf);//线程池
taskqueue.setParent( (ThreadPoolExecutor) executor);
lifecycle.fireLifecycleEvent(AFTER_START_EVENT, null);
}
1:
LinkedBlockingQueue一个基于已链接节点的、范围任意的 blocking queue。此队列按 FIFO(先进先出)排序元素。队列的头部 是在队列中时间最长的元素。队列的尾部 是在队列中时间最短的元素。新元素插入到队列的尾部,并且队列检索操作会获得位于队列头部的元素。链接队列的吞吐量通常要高于基于数组的队列,但是在大多数并发应用程序中,其可预知的性能要低。
2:TaskThreadFactory 是一个接口,主要负责创建新线程。个人感觉该类实现的不太好,但是还有待研究,线程知识有限!
class TaskThreadFactory implements ThreadFactory {
final ThreadGroup group;
final AtomicInteger threadNumber = new AtomicInteger(1);
final String namePrefix;
TaskThreadFactory(String namePrefix) {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
this.namePrefix = namePrefix;
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement());
t.setDaemon(daemon);
t.setPriority(getThreadPriority());
return t;
}
}
executor = new ThreadPoolExecutor(getMinSpareThreads(), getMaxThreads(), maxIdleTime, TimeUnit.MILLISECONDS,taskqueue, tf);//线程池
使用的构造函数为:
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory)
- 用给定的初始参数创建新的 ThreadPoolExecutor。
- 参数:
corePoolSize
- 池中所保存的线程数,包括空闲线程。maximumPoolSize
- 池中允许的最大线程数。keepAliveTime
- 当线程数大于核心时,此为终止前多余的空闲线程等待新任务的最长时间。unit
- keepAliveTime 参数的时间单位。workQueue
- 执行前用于保持任务的队列。此队列仅保持由 execute 方法提交的 Runnable 任务。threadFactory
- 执行程序创建新线程时使用的工厂。
execute方法如下:
public void execute(Runnable command) {
if ( executor != null ) {
try {
executor.execute(command);
} catch (RejectedExecutionException rx) {
//there could have been contention around the queue
if ( !( (TaskQueue) executor.getQueue()).force(command) ) throw new RejectedExecutionException();
}
} else throw new IllegalStateException("StandardThreadPool not started.");
}
需要参考书籍《java并发编程实践》Braian Goetz ,Tim Peierls. etc