A simple thread pool implementation

java 代码
  1. import java.util.Vector;   
  2.   
  3. /**  
  4.  * Thread pool  
  5.  */  
  6. public class ThreadPool implements Runnable {   
  7.   
  8.     // Default ThreadPool minimum size   
  9.     public final static int DEFAULT_MIN_SIZE = 0;   
  10.   
  11.     // Default ThreadPool maximum size   
  12.     public final static int DEFAULT_MAX_SIZE = Integer.MAX_VALUE;   
  13.   
  14.     public final static long DEFAULT_RELEASE_DELAY = 10 * 1000;   
  15.   
  16.     // customized thread pool minimum size   
  17.     protected int minSize;   
  18.   
  19.     // customized thread pool maximum size   
  20.     protected int maxSize;   
  21.   
  22.     protected long releaseDelay;   
  23.   
  24.     // current threads size in threadpool   
  25.     protected int currentSize;   
  26.        
  27.     protected int availableThreads;   
  28.   
  29.     // task list   
  30.     protected Vector taskList;   
  31.   
  32.     /**  
  33.      * customized ThradPool  
  34.      *   
  35.      * @param minSize  
  36.      *            minimum thread pool size  
  37.      * @param maxSize  
  38.      *            maximum thread pool size  
  39.      * @param releaseDelay  
  40.      *            threads release delay  
  41.      */  
  42.     public ThreadPool(int minSize, int maxSize, long releaseDelay) {   
  43.         this.minSize = minSize;   
  44.         this.maxSize = maxSize;   
  45.         this.releaseDelay = releaseDelay;   
  46.         taskList = new Vector(100);   
  47.         availableThreads = 0;   
  48.     }   
  49.   
  50.     /**  
  51.      * Default ThreadPool  
  52.      */  
  53.     public ThreadPool() {   
  54.         this(DEFAULT_MIN_SIZE, DEFAULT_MIN_SIZE, DEFAULT_RELEASE_DELAY);   
  55.     }   
  56.   
  57.     /**  
  58.      * set minimum thread pool size  
  59.      *   
  60.      * @param minSize  
  61.      *            minimum thread pool size  
  62.      */  
  63.     public synchronized void setMinSize(int minSize) {   
  64.         this.minSize = minSize;   
  65.     }   
  66.   
  67.     /**  
  68.      * get minimum thread pool size  
  69.      */  
  70.     public synchronized int getMinSize() {   
  71.         return minSize;   
  72.     }   
  73.   
  74.     /**  
  75.      * set maximum thread pool size  
  76.      *   
  77.      * @param maxSize  
  78.      *            maximum thread pool size  
  79.      */  
  80.     public synchronized void setMaxSize(int maxSize) {   
  81.         this.maxSize = maxSize;   
  82.     }   
  83.   
  84.     /**  
  85.      * get maximum thread pool size  
  86.      */  
  87.     public synchronized int getMaxSize() {   
  88.         return maxSize;   
  89.     }   
  90.   
  91.     /**  
  92.      * set thread release delay  
  93.      *   
  94.      * @param releaseDelay  
  95.      *            thread release delay time  
  96.      */  
  97.     public synchronized void setReleaseDelay(long releaseDelay) {   
  98.         this.releaseDelay = releaseDelay;   
  99.     }   
  100.   
  101.     /**  
  102.      * get thread release delay  
  103.      */  
  104.     public synchronized long getReleaseDelay() {   
  105.         return releaseDelay;   
  106.     }   
  107.   
  108.     /**  
  109.      * add a task to task list of ThreadPool  
  110.      *   
  111.      * @param runnable  
  112.      *            new task  
  113.      */  
  114.     public synchronized void addTask(Runnable runnable) {   
  115.   
  116.         taskList.addElement(runnable);   
  117.         if (availableThreads > 0) {   
  118.             this.notify();   
  119.         } else {   
  120.             if (currentSize < maxSize) {   
  121.                 Thread t = new Thread(this);   
  122.                 currentSize++;   
  123.                 t.start();   
  124.             }   
  125.         }   
  126.     }   
  127.   
  128.     public void run() {   
  129.         Runnable task;   
  130.         while (true) {   
  131.             synchronized (this) {   
  132.                 if (currentSize > maxSize) {   
  133.                     currentSize--;   
  134.                     break;   
  135.                 }   
  136.                 task = getNextTask();   
  137.                 if (task == null) {   
  138.                     try {   
  139.                         availableThreads++;   
  140.                         wait(releaseDelay);   
  141.                         availableThreads--;   
  142.                     } catch (InterruptedException ie) {   
  143.                         // do something you wanna   
  144.                     }   
  145.                     task = getNextTask();   
  146.                     if (task == null) {   
  147.                         if (currentSize < minSize)   
  148.                             continue;   
  149.                         currentSize--;   
  150.                         break;   
  151.                     }   
  152.                 }   
  153.             }   
  154.             try {   
  155.                 task.run();   
  156.             } catch (Exception e) {   
  157.                 System.err.println("Uncaught exception");   
  158.                 e.printStackTrace(System.err);   
  159.             }   
  160.         }   
  161.     }   
  162.   
  163.     /**  
  164.      * get the next task from task list.  
  165.      *   
  166.      */  
  167.     protected synchronized Runnable getNextTask() {   
  168.         Runnable task = null;   
  169.         if (taskList.size() > 0) {   
  170.             task = (Runnable) (taskList.elementAt(0));   
  171.             taskList.removeElementAt(0);   
  172.         }   
  173.         return task;   
  174.     }   
  175.   
  176.     /**  
  177.      * return thread pool message  
  178.      */  
  179.     public String toString() {   
  180.         StringBuffer sb = new StringBuffer();   
  181.         sb.append("DEFAULT_MIN_SIZE : " + DEFAULT_MIN_SIZE + "\n");   
  182.         sb.append("DEFAULT_MAX_SIZE : " + DEFAULT_MAX_SIZE + "\n");   
  183.         sb.append("DEFAULT_RELEASE_DELAY : " + DEFAULT_RELEASE_DELAY + "\n");   
  184.         sb.append("the information about your's construct ThreadPool below : \n");   
  185.         sb.append("minSize \t maxSize \t releaseDelay \n");   
  186.         sb.append(minSize + "\t" + maxSize + "\t" + releaseDelay);   
  187.   
  188.         return sb.toString();   
  189.     }   
  190.   
  191. }   
<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!-- Note: A "Server" is not itself a "Container", so you may not define subcomponents such as "Valves" at this level. Documentation at /docs/config/server.html --> -<Server shutdown="SHUTDOWN" port="8005"> <Listener className="org.apache.catalina.startup.VersionLoggerListener"/> <!-- Security listener. Documentation at /docs/config/listeners.html <Listener className="org.apache.catalina.security.SecurityListener" /> --> <!--APR library loader. Documentation at /docs/apr.html --> <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on"/> <!-- Prevent memory leaks due to use of particular java/javax APIs--> <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/> <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/> <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/> <!-- Global JNDI resources Documentation at /docs/jndi-resources-howto.html --> -<GlobalNamingResources> <!-- Editable user database that can also be used by UserDatabaseRealm to authenticate users --> <Resource pathname="conf/tomcat-users.xml" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" description="User database that can be updated and saved" type="org.apache.catalina.UserDatabase" auth="Container" name="UserDatabase"/> </GlobalNamingResources> <!-- A "Service" is a collection of one or more "Connectors" that share a single "Container" Note: A "Service" is not itself a "Container", so you may not define subcomponents such as "Valves" at this level. Documentation at /docs/config/service.html --> -<Service name="Catalina"> <!--The connectors can use a shared executor, you can define one or more named thread pools--> <!-- <Executor name="tomcatThreadPool" namePrefix="catalina-exec-" maxThreads="150" minSpareThreads="4"/> --> <!-- A "Connector" represents an endpoint by which requests are received and responses are returned. Documentation at : Java HTTP Connector: /docs/config/http.html Java AJP Connector: /docs/config/ajp.html APR (HTTP/AJP) Connector: /docs/apr.html Define a non-SSL/TLS HTTP/1.1 Connector on port 8080 --> <Connector port="8080" redirectPort="8443" connectionTimeout="20000" protocol="HTTP/1.1"/> <!-- A "Connector" using the shared thread pool--> <!-- <Connector executor="tomcatThreadPool" port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" /> --> <!-- Define an SSL/TLS HTTP/1.1 Connector on port 8443 This connector uses the NIO implementation. The default SSLImplementation will depend on the presence of the APR/native library and the useOpenSSL attribute of the AprLifecycleListener. Either JSSE or OpenSSL style configuration may be used regardless of the SSLImplementation selected. JSSE style configuration is used below. --> <!-- <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol" maxThreads="150" SSLEnabled="true"> <SSLHostConfig> <Certificate certificateKeystoreFile="conf/localhost-rsa.jks" type="RSA" /> </SSLHostConfig> </Connector> --> <!-- Define an SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2 This connector uses the APR/native implementation which always uses OpenSSL for TLS. Either JSSE or OpenSSL style configuration may be used. OpenSSL style configuration is used below. --> <!-- <Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol" maxThreads="150" SSLEnabled="true" > <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" /> <SSLHostConfig> <Certificate certificateKeyFile="conf/localhost-rsa-key.pem" certificateFile="conf/localhost-rsa-cert.pem" certificateChainFile="conf/localhost-rsa-chain.pem" type="RSA" /> </SSLHostConfig> </Connector> --> <!-- Define an AJP 1.3 Connector on port 8009 --> <!-- <Connector protocol="AJP/1.3" address="::1" port="8009" redirectPort="8443" /> --> <!-- An Engine represents the entry point (within Catalina) that processes every request. The Engine implementation for Tomcat stand alone analyzes the HTTP headers included with the request, and passes them on to the appropriate Host (virtual host). Documentation at /docs/config/engine.html --> <!-- You should set jvmRoute to support load-balancing via AJP ie : <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1"> --> -<Engine name="Catalina" defaultHost="localhost"> <!--For clustering, please take a look at documentation at: /docs/cluster-howto.html (simple how to) /docs/config/cluster.html (reference documentation) --> <!-- <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/> --> <!-- Use the LockOutRealm to prevent attempts to guess user passwords via a brute-force attack --> -<Realm className="org.apache.catalina.realm.LockOutRealm"> <!-- This Realm uses the UserDatabase configured in the global JNDI resources under the key "UserDatabase". Any edits that are performed against this UserDatabase are immediately available for use by the Realm. --> <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/> </Realm> -<Host name="localhost" autoDeploy="true" unpackWARs="true" appBase="webapps"> <!-- SingleSignOn valve, share authentication between web applications Documentation at: /docs/config/valve.html --> <!-- <Valve className="org.apache.catalina.authenticator.SingleSignOn" /> --> <!-- Access log processes all example. Documentation at: /docs/config/valve.html Note: The pattern used is equivalent to using pattern="common" --> <Valve className="org.apache.catalina.valves.AccessLogValve" pattern="%h %l %u %t "%r" %s %b" suffix=".txt" prefix="localhost_access_log" directory="logs"/> </Host> </Engine> </Service> </Server>https链接
06-27
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值