对 ThreadPool 的理解

虽然从 Java5 开始 JDK 里的 java.util.concurrent 包内建了线程池,你不必自己实现线程池,但理解线程的实现原理对 Java 编程很有用。 
当你想把运行在你的程序中的线程控制在一定的数量之内,线程池就显得非常有用。 

引用

原理: 

用一个阻塞队列里(Blocking Queue)来存储线程池的所有空闲线程。不用为每个任务都创建一个新的线程,可以把任务当参数传到线程池里。只要当线程池有空闲的线程时,这个任务就会被执行。 


BlockQueue.java 
Java代码 
  1. public class BlockingQueue {  
  2.   
  3.     private List queue = new LinkedList();  
  4.     private int limit = 10;  
  5.   
  6.     public BlockingQueue(int limit) {  
  7.         this.limit = limit;  
  8.     }  
  9.   
  10.     public synchronized Object enqueue(Object item)  
  11.             throws InterruptedException {  
  12.         while (this.queue.size() == this.limit) {  
  13.             System.out.println("Arrive to the pool's max size:"+this.limit);  
  14.             wait();  
  15.         }  
  16.         if (this.queue.size() == 0) {  
  17.             notifyAll();  
  18.         }  
  19.   
  20.         System.out.println("Add a new thread to the pool.Pool's size before   
  21.   
  22. adding:"+this.queue.size());  
  23.         this.queue.add(item);  
  24.           
  25.         return this.queue.get(this.queue.size()-1);  
  26.     }  
  27.   
  28.     public synchronized Object dequeue()  
  29.             throws InterruptedException {  
  30.         while (this.queue.size() == 0) {  
  31.             System.out.println("Pool's size is 0.");  
  32.             wait();  
  33.         }  
  34.         if (this.queue.size() == this.limit) {  
  35.             notifyAll();  
  36.         }  
  37.   
  38.         System.out.println("Remove a thread from the pool.Pool's size before   
  39.   
  40. removing:"+(this.queue.size()-1));  
  41.         return this.queue.remove(0);  
  42.     }  
  43.       
  44.     public synchronized int size(){  
  45.         return this.queue.size();  
  46.     }  
  47. }  

当阻塞队列没达到界限值(最大值与最小值)时,插入与出列正常,没限制。阻塞队列达到最大值时,再想插入一个线程,队列就会停止操作,让插入在等待,同时唤醒出列操作。相反,当全部出列后,再想出列时,出列操作就会停止,在等待,同时唤醒插入操作。 


线程池通常用在多线程服务端的,下边是实现线程池的其他类,其中: 
Java代码 
  1. /** 
  2.  * Implements the thread pool 
  3.  * @author winxp 
  4.  */  
  5. public class ThreadPool {  
  6.   
  7.     private BlockingQueue taskQueue = null;  
  8.     private List<TaskThread> threads = new ArrayList<TaskThread>();  
  9.     private boolean isStopped = false;  
  10.   
  11.     /** 
  12.      * Create a new ThreadPool 
  13.      * @param noOfThreads Initiate num of threads in the thread pool线程池的初始化线程数 
  14.      * @param maxNoOfTasks Max num of threads in the thread pool线程池的最大线程数 
  15.      */  
  16.     public ThreadPool(int noOfThreads, int maxNoOfTasks) {  
  17.         taskQueue = new BlockingQueue(maxNoOfTasks);  
  18.   
  19.         for (int i = 0; i < noOfThreads; i++) {  
  20.             threads.add(new TaskThread(taskQueue));  
  21.         }  
  22.         for (TaskThread thread : threads) {  
  23.             thread.start();  
  24.         }  
  25.     }  
  26.       
  27.     /** 
  28.      * 
  29.      * @param task 
  30.      */  
  31.     public synchronized void execute(Runnable task){  
  32.         if(this.isStopped)throw   
  33.                 new IllegalStateException("ThreadPool is stopped");  
  34.         try {  
  35.             this.taskQueue.enqueue(task);  
  36.         } catch (InterruptedException ex) {  
  37.            ex.printStackTrace();  
  38.         }  
  39.     }  
  40.   
  41.     /** 
  42.      * 
  43.      */  
  44.     public synchronized void stop() {  
  45.         this.isStopped = true;  
  46.         for (TaskThread thread : threads) {  
  47.             thread.interrupt();  
  48.         }  
  49.     }  
  50. }  
  51.   
  52. /** 
  53.  * Simulate that dequeue from the BlockingQueue, and execute the dequeuing task 
  54.  */  
  55. public class TaskThread extends Thread {  
  56.   
  57.     private BlockingQueue taskQueue = null;  
  58.     private boolean isStopped = false;  
  59.   
  60.     public TaskThread(BlockingQueue queue) {  
  61.         taskQueue = queue;  
  62.     }  
  63.   
  64.     @Override  
  65.     public void run() {  
  66.         while (!isStopped()) {  
  67.             try {  
  68.                 Runnable runnable = (Runnable) taskQueue.dequeue();  
  69.                 runnable.run();  
  70.             } catch (Exception e) {  
  71.                 //log or otherwise report exception,  
  72.                 //but keep pool thread alive.  
  73.             }  
  74.         }  
  75.     }  
  76.       
  77.     @Override  
  78.     public synchronized void interrupt() {  
  79.         isStopped = true;  
  80.         super.interrupt();//break pool thread out of dequeue() call.  
  81.     }  
  82.   
  83.     public synchronized boolean isStopped() {  
  84.         return isStopped;  
  85.     }  
  86. }  


测试类: 
Java代码 
  1. /** 
  2.  * Testing class 
  3.  */  
  4. class TestThread extends Thread{  
  5.     private int num;  
  6.     public TestThread(int num){  
  7.         this.num = num;  
  8.     }  
  9.       
  10.     @Override  
  11.     public void run(){  
  12.         System.out.println("TestThread index: "+num);  
  13.         try {  
  14.             Thread.sleep(1000);  
  15.         } catch (InterruptedException ex) {  
  16.         }  
  17.     }  
  18.   
  19.     /** 
  20.      * 
  21.      * @param args 
  22.      */  
  23.     public static void main(String[] args){  
  24.         ThreadPool tp = new ThreadPool(3,10);  
  25.         for(int i = 0;i<15;i++){  
  26.             TestThread test = new TestThread(i);  
  27.             tp.execute(test);  
  28.         }  
  29.     }  
  30. }  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值