菜鸟代码,寻指教

今天看了下线程池,觉得挺有意思,自己写了一个,不知道有没有理解错,希望大家指点下,给点宝贵意见建议~





public interface Job {
public void run();
}





import java.util.Stack;

/**

  • 线程池
  • @author xmj
    *
    */
    public class ThreadPool{
    private int maxThread; //最大线程数
    private int currThreadCount; //当前线程数
    private Stack waitstack; //空闲线程栈

    /**

    • @param max 线程池最大线程数
    • @param job 线程工作类 */ public ThreadPool(int max) { this.maxThread=max; this.currThreadCount=0; this.waitstack=new Stack(); MyThread[] threads=new MyThread[max]; for(int i=0;i<max;i++) { threads[i]=new MyThread(i); waitstack.add(threads[i]); threads[i].start(); } }

    /**

    • @author xmj
    • 内部线程类
      *
      */
      private class MyThread extends Thread
      {
      private int id; //线程ID
      private Job job; //任务
      private boolean stop=false; //停止标志

      public MyThread(int id)
      {
      this.id=id;
      }
      /**

      • @param job 任务 */ public void setJob(Job job) { this.job=job; }

      /**

      • 停止线程 * */ public void threadstop() { stop=true; }

      public void run()
      {
      while(!stop)
      {
      if(job==null)
      {
      //没任务就进入等待
      synchronized(this){
      try {
      wait();
      } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      }
      }
      }
      else
      {
      job.run();//运行作业

              /**
               * 如果该线程不是扩展线程,则清空任务,继续等待,并入栈
               * 否则结束
               */
              if(this.id&lt;=maxThread)
              {
                  job=null;
              }
          }
      }
      currThreadCount--;
      

      }
      }

    /**

    • 添加新线程任务
    • @param job 任务 */ public void addJob(Job job) { currThreadCount++; if(waitstack.isEmpty()) { MyThread exThread=new MyThread(currThreadCount); exThread.start(); } else { MyThread t=(MyThread)waitstack.pop(); t.setJob(job); synchronized(t){ t.notify(); } } }

    /**

    • 回收线程
    • @param t 完成任务的线程
    • */ public void push(MyThread t) { waitstack.push(t); currThreadCount--; }

    /**

    • 清理工作 * */ public void kill() { while(currThreadCount!=0) { while(!waitstack.isEmpty()) { MyThread t=(MyThread)waitstack.pop(); t.threadstop(); t.notify(); currThreadCount--; } waitstack=null; } }

}


问题补充
各位老大,给点意见啊~~~

代码就不细看了,你理解上的线程池是没什么问题的
可能多考虑一些非功能需求,比如性能问题,异常情况,如果一个线程挂了,是不是还要新建一个线程来补充之类的

问题的关键就是“池”这个字,各种池都是差不多的,不同级别的开源实现有很多,你要的答案就在那些代码里

                /**  
                 * 如果该线程不是扩展线程,则清空任务,继续等待,并入栈  
                 * 否则结束  
                 */  
                if(this.id<=maxThread)   
                {   
                    job=null;   
                } else {
                    stop = true;
                }

看注释这里楼主是否少加了句?