1 7 package org.jboss.mq.threadpool; 8 9 import java.lang.Thread ; 10 import java.lang.ThreadGroup ; 11 12 import java.util.ArrayList ; 13 import java.util.LinkedList ; 14 15 16 23 public class ThreadPool 24 { 25 28 private String name; 29 30 33 private boolean daemon; 34 35 38 private ThreadGroup threadGroup; 39 40 43 private ArrayList workers; 44 45 48 private int maxWorkers; 49 50 54 private int idleWorkers; 55 56 60 private volatile boolean stopping; 61 62 65 private LinkedList queue; 66 67 68 79 public ThreadPool(String name, ThreadGroup threadGroup, int maxWorkers, 80 boolean daemon) 81 { 82 if (name == null || threadGroup == null || maxWorkers <= 0) 83 throw new IllegalArgumentException (); 84 85 this.name = name; 86 this.daemon = daemon; 87 this.threadGroup = threadGroup; 88 workers = new ArrayList (); 89 this.maxWorkers = maxWorkers; 90 idleWorkers = 0; 91 stopping = false; 92 queue = new LinkedList (); 93 } 94 95 101 public void shutdown() 102 { 103 stopping = true; 104 105 synchronized (queue) { 106 queue.clear(); 108 queue.notifyAll(); 110 } 111 112 synchronized (workers) { 114 while (workers.size() > 0) { 115 try { 116 workers.wait(); 118 } catch (InterruptedException ex) { 119 } 121 } 122 } 123 } 124 125 126 135 public void enqueueWork(Work work) 136 { 137 synchronized (workers) { 140 if (idleWorkers == 0 && !stopping && workers.size() < maxWorkers) 143 { 144 new WorkerThread(name + "-" + (workers.size() + 1)).start(); 145 } 147 } 148 149 synchronized (queue) { 150 if (stopping) 151 return; 153 queue.addLast(work); 154 queue.notify(); 156 } 157 } 158 159 164 public void cancelWork(Work work) 165 { 166 synchronized (queue) { 167 while (queue.remove(work)) 169 ; 170 } 171 } 172 173 174 177 private class WorkerThread 178 extends Thread 179 { 180 184 WorkerThread(String name) 185 { 186 super(threadGroup, name); 187 setDaemon(daemon); 188 workers.add(this); 189 } 191 192 198 private void idle() 199 { 200 try { 201 synchronized (workers) { 202 ++idleWorkers; 203 } 204 queue.wait(); 206 } catch (InterruptedException ex) { 207 } finally { 209 synchronized (workers) { 211 --idleWorkers; 212 } 213 } 214 } 215 216 public void run() 217 { 218 while (!stopping) { 220 Work work = null; 221 222 synchronized (queue) { 223 if (queue.size() == 0) 224 idle(); 225 if (!stopping && queue.size() > 0) 226 work = (Work)queue.removeFirst(); 227 } 228 229 if (work != null) 230 work.doWork(); 231 } 232 synchronized (workers) { 233 workers.remove(this); 234 workers.notify(); 236 } 237 } 238 } 239 } 240 | Popular Tags |