1 4 package org.oddjob.util; 5 6 7 12 public class ThreadPool { 13 14 private BlockingQueue queue = new BlockingQueue(); 15 private boolean closed = true; 16 17 private int poolSize = 3; 18 19 20 public void setPoolSize(int poolSize) { 21 this.poolSize = poolSize; 22 } 23 24 public int getPoolSize() { 25 return poolSize; 26 } 27 28 synchronized public void start() { 29 if (!closed) { 30 throw new IllegalStateException ("Pool already started."); 31 } 32 closed = false; 33 for (int i = 0; i < poolSize; ++i) { 34 new PooledThread().start(); 35 } 36 } 37 38 synchronized public void execute(Runnable job) { 39 if (closed) { 40 throw new PoolClosedException(); 41 } 42 queue.enqueue(job); 43 } 44 45 private class PooledThread extends Thread { 46 47 public void run() { 48 while (true) { 49 Runnable job = (Runnable ) queue.dequeue(); 50 if (job == null) { 51 break; 52 } 53 try { 54 job.run(); 55 } catch (Throwable t) { 56 } 58 } 59 } 60 } 61 62 public void close() { 63 closed = true; 64 queue.close(); 65 } 66 67 private static class PoolClosedException extends RuntimeException { 68 PoolClosedException() { 69 super ("Pool closed."); 70 } 71 } 72 } 73 | Popular Tags |