正文

一个简单的线程池2006-05-09 16:06:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/sword2008/13779.html

分享到:

此代码来自《java游戏编程》,北京希望电子出版社。David Brackeen著 邱仲潘译。线程池的入门代码。站长整理。 import java.util.LinkedList; public class ThreadPool extends ThreadGroup {//作为线程组来实现线程池,新颖     private boolean isAlive;//此线程池是否激活     private LinkedList taskQueue;//存放任务的链表     private int threadID;//线程池中的线程数     private static int threadPoolID;//用来记数,实例化了多少个线程池对象     /**         创建一个新的线程池.         @param numThreads 池中的线程数.     */     public ThreadPool(int numThreads) {         super("ThreadPool-" + (threadPoolID++));         setDaemon(true);         isAlive = true;         taskQueue = new LinkedList();         for (int i=0; i<numThreads; i++) {             new PooledThread().start();//启动numThreads个线程用于执行存于链表中的任务         }     }          public synchronized void runTask(Runnable task) {//往链表中添加任务的方法         if (!isAlive) {             throw new IllegalStateException();         }         if (task != null) {             taskQueue.add(task);//添加任务             notify();//通知等待的线程         }     }     protected synchronized Runnable getTask()//在链表中取任务         throws InterruptedException     {         while (taskQueue.size() == 0) {             if (!isAlive) {                 return null;             }             wait();//如果链表中没有任务,等待         }         return (Runnable)taskQueue.removeFirst();//取出任务     }     /**         关闭这个线程池并立即返回。所有线程停止,不执行任何等待的任务。     */     public synchronized void close() {         if (isAlive) {             isAlive = false;             taskQueue.clear();             interrupt();         }     }     /**         关闭这个线程池,并等待所有运行的线程完成,执行任何等待的任务。     */     public void join() {         //通知所有等待的线程,这个线程不再活动         synchronized (this) {             isAlive = false;             notifyAll();         }         //等待所有线程完成         Thread[] threads = new Thread[activeCount()];         int count = enumerate(threads);         for (int i=0; i<count; i++) {             try {                 threads[i].join();             }             catch (InterruptedException ex) { }         }     }     /**         PooledThread是在线程池中的一个线程,用于运行任务(Runnables).     */     private class PooledThread extends Thread {//私有的,内部才能实例化         public PooledThread() {             super(ThreadPool.this,                 "PooledThread-" + (threadID++));         }         public void run() {//启动线程时执行的方法          while (!isInterrupted()) {//线程池的关键之处,池中每一个线程只要没有中断,都循环执行任务                 // get a task to run                 Runnable task = null;                 try {                     task = getTask();//可能需要等待                 }                 catch (InterruptedException ex) { }                 // if getTask() returned null or was interrupted,                 // close this thread by returning.                 if (task == null) {                     return;                 }                 // run the task, and eat any exceptions it throws                 try {                     task.run();                 }                 catch (Throwable t) {                     uncaughtException(this, t);                 }//任务处理完毕             }//此线程继续循环,等待或执行任务。         }     } } 以下是测试程序: public class ThreadPoolTest {     public static void main(String[] args) {         if (args.length != 2) {             System.out.println("Tests the ThreadPool task.");             System.out.println(                 "Usage: java ThreadPoolTest numTasks numThreads");             System.out.println(                 "  numTasks - integer: number of task to run.");             System.out.println(                 "  numThreads - integer: number of threads " +                 "in the thread pool.");             return;         }         int numTasks = Integer.parseInt(args[0]);//需要运行的任务数         int numThreads = Integer.parseInt(args[1]);//线程池中启动的线程数         // create the thread pool         ThreadPool threadPool = new ThreadPool(numThreads);//生成线程池,启动线程池中的线程         // run example tasks         for (int i=0; i<numTasks; i++) {             threadPool.runTask(createTask(i));//往线程池中加任务         }         // 关闭池并等待完成所有任务.         threadPool.join();     }     /**         创建简单任务.     */     private static Runnable createTask(final int taskID) {         return new Runnable() {             public void run() {                 System.out.println("Task " + taskID + ": start");                 // simulate a long-running task                 try {                     Thread.sleep(500);                 }                 catch (InterruptedException ex) { }                 System.out.println("Task " + taskID + ": end");             }         };     } } 运行: C:\java>java   ThreadPoolTest 8 4 Task 0: start Task 1: start Task 2: start Task 3: start Task 0: end Task 4: start Task 2: end Task 5: start Task 3: end Task 6: start Task 1: end Task 7: start Task 4: end Task 5: end Task 6: end Task 7: end C:\java>

阅读(4498) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册