服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

一个非常简单,非常短小的线程池

最近写了一个 http 代理服务器,发现访问网页时建立的连接很多,消耗的线程也非常的多,对于系统是

一个不小的开销.而且这些线程存在的时间都很短,99%以上的线程存在的时间都在毫秒的等级,相对来说

线程的建立的注销就占了绝大部分的cpu时间.
因此,在网上搜了一下线程池的资料,发现里面的东西不是太大太复杂,就是写得太烂,根本没有一点专业

水准.
没办法,只好自己简单的学习了一下 wait()/notify()机制,写了一个很小的线程池.
代码如下(一共2个类):
/*
 *一个简单的线程池 threadpool .java
 */
public class threadpool {
 //以下是配置信息,可以更改
 static int max_thread = 1000; //未使用
 static int min_thread = 14;
 
 static int id = 1; //线程 id 号,主要用于监视线程的工作情况
 
 static private threadpool pool = new threadpool();
 static public threadpool getthreadpool() {
  return pool;
 }
 
 stack<workthread> stack = new stack<workthread>(min_thread);
 private threadpool() {
 }
 
 synchronized public boolean putworkthread(workthread wt) {
  if(stack.size()<min_thread){
   stack.push(wt);
   return true;
  } else {
   return false;
  }
 }
 
 synchronized public workthread getworkthread() {
  workthread wt = null;
  if(stack.isempty()) {
   wt = new workthread(this);
   new thread(wt,"线程id:"+id).start();
   id++;
  } else {
   wt = stack.pop();
  }
  return wt;
 }
}
--------------------------------------------------------------------------
/*
 *工作线程类 workthread.java
 */
public class workthread implements runnable {
 object lock = new object();
 runnable runner = null;
 threadpool pool = null;
 
 public workthread(threadpool pool) {
  this.pool = pool;
 }
 
 public void start(runnable r) {
  runner = r;
  synchronized(lock) {
   lock.notify();
  }
 }
 
 public void run() {
  while(true) {
   if(runner != null) {
    runner.run();
    runner = null; //及时回收资源
   }
   if(pool.putworkthread(this)) {
    system.out.println (thread.currentthread().getname()+" 被回收!");
    synchronized(lock) {
     try {
      lock.wait();
     } catch (interruptedexception ie) {
      system.out.println ("停止线程时出现异常");
     }
    }
   } else {
    system.out.println (thread.currentthread().getname()+" 被丢弃!");
    break;
   }
  }
 }
}

使用方法:
runnable r = ......;
new thread(r).start();
这是你以前的代码,使用线程池只需要将后一句变成
threadpool.getthreadpool().getworkthread().start(r);
就可以了,其他的代码不用任何更改.

这个线程池还有两个功能没有实现:
1.最大线程数的控制
2.空闲线程等待一定时间后自动注销
但这个线程池也有一个好处--可以随时改变最小线程的数量.

由于学 java 不太懂,其中可能有不太完善的地方,还请各位高手指点一下,谢谢!!

扫描关注微信公众号