一个简单的线程池ThreadPool

本文介绍了一种基于Java实现的线程池结构,通过自定义线程组的方式管理多个线程,有效地分配任务并控制线程数量。文章详细展示了线程池的创建过程及任务调度机制,包括任务队列管理、线程生命周期控制等关键环节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值