tomcat 7 源码分析-10 线程池ThreadPoolExecutor
tomcat 7 源码分析-10 线程池ThreadPoolExecutor
tomcat开启socket的accept线程后,其实要做的主要工作是交给worker线程去完成的,这其中使用了线程池的技术。
如:
try { SocketWrapper<Socket> wrapper = new SocketWrapper<Socket>(socket); wrapper.setKeepAliveLeft(getMaxKeepAliveRequests()); getExecutor().execute(new SocketProcessor(wrapper)); }
try { SocketWrapper<Socket> wrapper = new SocketWrapper<Socket>(socket); wrapper.setKeepAliveLeft(getMaxKeepAliveRequests()); getExecutor().execute(new SocketProcessor(wrapper)); }
事实上tomcat对ThreadPoolExecutor做了一点小小的封装。
先来看一个简单的java api——ThreadPoolExecutor的使用
package com.test.threadpool; import java.util.concurrent.*; public class ThreadpoolTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int minSpareThreads = 10 ; int maxThreads = 200 ; LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>(); ThreadPoolExecutor executor = new ThreadPoolExecutor(minSpareThreads, maxThreads, 60 , TimeUnit.SECONDS,workQueue); for ( int i = 0 ; i <= 5 ; i++) { //创建6个任务 executor.execute(createTask(i)); } executor.shutdown(); } private static Runnable createTask( final int taskID) { return new Runnable() { public void run() { System.out.println("Task" + taskID + "开始" ); System.out.println("Hello world" ); System.out.println("Task" + taskID + "结束" ); } }; } }
package com.test.threadpool; import java.util.concurrent.*; public class ThreadpoolTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int minSpareThreads = 10; int maxThreads = 200; LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>(); ThreadPoolExecutor executor = new ThreadPoolExecutor(minSpareThreads, maxThreads, 60, TimeUnit.SECONDS,workQueue); for (int i = 0; i <=5 ; i++) { //创建6个任务 executor.execute(createTask(i)); } executor.shutdown(); } private static Runnable createTask(final int taskID) { return new Runnable() { public void run() { System.out.println("Task" + taskID + "开始"); System.out.println("Hello world"); System.out.println("Task" + taskID + "结束"); } }; } }
所要执行的任务,只要是Runnable,然后交给executor执行,显得很简单。
tomcat对其封装在package org.apache.tomcat.util.threads中,可以看看
相关推荐
ljngya 2020-07-30
齐天大圣数据候 2020-07-30
爱传文档 2020-07-28
jameszgw 2020-06-25
fengling 2020-05-31
meylovezn 2020-05-30
大步流星 2020-05-28
Ken专注后端技术 2020-05-07
nurvnurv 2020-05-01
cenylon 2020-04-29
fengyeezju 2020-04-26
csde 2020-03-05
nbfcome 2020-02-21
huaye00 2020-02-18
xdhywj 2020-02-13
greensomnuss 2012-09-11
xzkjgw 2020-01-23
少年阿涛 2020-01-12
MichelinMessi 2020-01-07