1 package net.javacoding.jspider.core.threading; 2 3 4 import net.javacoding.jspider.core.task.DispatcherTask; 5 import net.javacoding.jspider.core.task.WorkerTask; 6 7 8 16 public class WorkerThreadPool extends ThreadGroup { 17 18 19 protected DispatcherThread dispatcherThread; 20 21 22 protected WorkerThread[] pool; 23 24 25 protected int poolSize; 26 27 33 public WorkerThreadPool(String poolName, String threadName, int poolSize) { 34 super(poolName); 35 36 this.poolSize = poolSize; 37 38 dispatcherThread = new DispatcherThread(this, threadName + " dispatcher", this); 39 pool = new WorkerThread[poolSize]; 40 for (int i = 0; i < poolSize; i++) { 41 pool[i] = new WorkerThread(this, threadName, i); 42 synchronized (this) { 43 try { 44 pool[i].start(); 45 wait(); 46 } catch (InterruptedException e) { 47 Thread.currentThread().interrupt(); 48 } 49 } 50 } 51 } 52 53 58 public synchronized void assign(WorkerTask task) { 59 while (true) { 60 for (int i = 0; i < poolSize; i++) { 61 if (pool[i].isAvailable()) { 62 pool[i].assign(task); 63 return; 64 } 65 } 66 try { 67 wait(); 68 } catch (InterruptedException e) { 69 Thread.currentThread().interrupt(); 70 } 71 } 72 } 73 74 79 public void assignGroupTask(DispatcherTask task) { 80 dispatcherThread.assign(task); 81 } 82 83 87 public int getOccupation() { 88 int occupied = 0; 89 for (int i = 0; i < poolSize; i++) { 90 WorkerThread thread = pool[i]; 91 if (thread.isOccupied()) { 92 occupied++; 93 } 94 } 95 return (occupied * 100) / poolSize; 96 } 97 98 public int getBlockedPercentage() { 99 int counter = 0; 100 for (int i = 0; i < poolSize; i++) { 101 WorkerThread thread = pool[i]; 102 if (thread.getState() == WorkerThread.WORKERTHREAD_BLOCKED ) { 103 counter++; 104 } 105 } 106 return (counter * 100) / poolSize; 107 } 108 109 public int getBusyPercentage () { 110 int counter = 0; 111 for (int i = 0; i < poolSize; i++) { 112 WorkerThread thread = pool[i]; 113 if (thread.getState() == WorkerThread.WORKERTHREAD_BUSY) { 114 counter++; 115 } 116 } 117 return (counter * 100) / poolSize; 118 } 119 120 public int getIdlePercentage ( ) { 121 int counter = 0; 122 for (int i = 0; i < poolSize; i++) { 123 WorkerThread thread = pool[i]; 124 if (thread.getState() == WorkerThread.WORKERTHREAD_IDLE ) { 125 counter++; 126 } 127 } 128 return (counter * 100) / poolSize; 129 } 130 131 134 public void stopAll() { 135 for (int i = 0; i < pool.length; i++) { 136 WorkerThread thread = pool[i]; 137 thread.stopRunning(); 138 } 139 } 140 141 145 public int getSize ( ) { 146 return poolSize; 147 } 148 149 } 150 | Popular Tags |