线程池的体验,这里是简单的例子,不解释了,只能意会不能言传。
 
//第一个类
package thread;
import java.util.LinkedList;
public class ThreadPool {
  private LinkedList tasks = new LinkedList();
  public ThreadPool(int size) {
    for (int i = 0; i < size; i++) {
     System.out.println("new");
      Thread thread = new ThreadTask(this);
      thread.start();
    }
  }
  public void run(Runnable task) {
   System.out.println("run0");
    synchronized (tasks) {
      tasks.addLast(task);
      tasks.notify();
    }
  }
  public Runnable getNext() {
    Runnable returnVal = null;
    synchronized (tasks) {
      while (tasks.isEmpty()) {
        try {
         System.out.println("waiting");
         Thread.sleep(1000);
          tasks.wait();
          System.out.println("waited");
        } catch (InterruptedException ex) {
          System.err.println("Interrupted");
        }
      }
      returnVal = (Runnable) tasks.removeFirst();
    }
    return returnVal;
  }
  public static void main(String args[]) {
    final String message[] = { "zgw", "nake", "sunny", "piao" };
    ThreadPool pool = new ThreadPool(message.length / 1);
    for (int i = 0, n = message.length; i < n; i++) {
      final int innerI = i;
      Runnable  runner = new Runnable() {
        public void run() {
          for (int j = 0; j < 25; j++) {
            System.out.println("j: " + j + ": " + message[innerI]+"   "+innerI);
          }
        }
      };
      
     pool.run(runner);
    }
  }
}
//---------------------
第二个类
package thread;
import java.util.LinkedList;
class ThreadTask extends Thread {
  private ThreadPool pool;
  public ThreadTask(ThreadPool thePool) {
    pool = thePool;
  }
  public void run() {
    while (true) {
     System.out.println("gogogo");
      // blocks until job
      Runnable job = pool.getNext();
      try {
        job.run();
      } catch (Exception e) {
        System.err.println("Job exception: " + e);
      }
    }
  }
}
	posted on 2006-01-08 22:58 
nake 阅读(300) 
评论(0)  编辑  收藏