posts - 39,  comments - 263,  trackbacks - 0

线程池的体验,这里是简单的例子,不解释了,只能意会不能言传。

 

//第一个类
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 阅读(284) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航:
 
<2006年1月>
25262728293031
1234567
891011121314
15161718192021
22232425262728
2930311234

常用链接

留言簿(18)

我参与的团队

随笔档案(39)

收藏夹(1)

搜索

  •  

积分与排名

  • 积分 - 450857
  • 排名 - 118

最新评论

阅读排行榜

评论排行榜