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中,可以看看

相关推荐