1 package org.jacorb.util.threadpool; 2 3 23 24 import java.util.*; 25 26 35 public class ThreadPool 36 { 37 private int max_threads = 0; 38 private int max_idle_threads = 0; 39 40 private int total_threads = 0; 41 private int idle_threads = 0; 42 43 private LinkedList job_queue = null; 44 private ConsumerFactory factory = null; 45 46 public ThreadPool( ConsumerFactory factory ) 47 { 48 this( new LinkedList (), 49 factory, 50 10, 51 10 ); 52 } 53 54 public ThreadPool( ConsumerFactory factory, 55 int max_threads, 56 int max_idle_threads) 57 { 58 this 59 ( 60 new LinkedList (), 61 factory, 62 max_threads, 63 max_idle_threads 64 ); 65 } 66 67 private ThreadPool( LinkedList job_queue, 68 ConsumerFactory factory, 69 int max_threads, 70 int max_idle_threads) 71 { 72 this.job_queue = job_queue; 73 this.factory = factory; 74 this.max_threads = max_threads; 75 this.max_idle_threads = max_idle_threads; 76 } 77 78 protected synchronized Object getJob() 79 { 80 85 if (idle_threads >= max_idle_threads) 86 { 87 total_threads--; 88 return null; 89 } 90 91 idle_threads++; 92 93 while( job_queue.isEmpty() ) 94 { 95 try 96 { 97 wait(); 98 } 99 catch( InterruptedException e ) 100 { 101 } 102 } 103 104 return job_queue.removeFirst(); 105 } 106 107 public synchronized void putJob( Object job ) 108 { 109 job_queue.add(job); 110 notifyAll(); 111 112 if(idle_threads <= 0) 114 { 115 if(total_threads < max_threads) 116 { 117 createNewThread(); 118 119 idle_threads--; 122 } 123 } 124 else 125 { 126 idle_threads--; 129 } 130 } 131 132 private void createNewThread() 133 { 134 Thread t = 135 new Thread ( new ConsumerTie( this, factory.create() )); 136 t.setDaemon( true ); 137 t.start(); 138 139 total_threads++; 140 } 141 } | Popular Tags |