1 31 package org.objectweb.proactive.core.group.threadpool; 32 33 import org.objectweb.proactive.core.group.AbstractProcessForGroup; 34 35 import java.util.ArrayList ; 36 37 38 42 public class ThreadPool { 43 44 45 private Thread [] threads = null; 46 47 48 private ArrayList pendingJobs = null; 49 50 51 protected EndControler controler = new EndControler(); 52 53 54 private int memberToThreadRatio = 4; 55 56 59 public ThreadPool() { 60 this(1); 61 } 62 63 66 public ThreadPool(int size) { 67 this.threads = new ThreadInThePool[size]; 68 this.pendingJobs = new ArrayList (size); 69 for (int i = 0; i < this.threads.length; i++) { 70 this.threads[i] = new ThreadInThePool(this); 71 this.threads[i].start(); 72 } 73 } 74 75 79 protected void createThreads(int number) { 80 this.threads = new ThreadInThePool[number]; 81 for (int i = 0; i < this.threads.length; i++) { 82 this.threads[i] = new ThreadInThePool(this); 83 this.threads[i].start(); 84 } 85 } 86 87 92 public void checkNumberOfThreads(int members) { 93 if (members > (this.memberToThreadRatio * this.threads.length)) { 94 int i; 95 int f = (int) Math.ceil(((float) members) / ((float) this.memberToThreadRatio)); 96 Thread [] tmp = new Thread [f]; 97 98 for (i = 0; i < this.threads.length; i++) { 99 tmp[i] = this.threads[i]; 100 } 101 for (; i < f; i++) { 102 tmp[i] = new ThreadInThePool(this); 103 tmp[i].start(); 104 } 105 this.threads = tmp; 106 } else if (members < (this.memberToThreadRatio * this.threads.length)) { 107 int i; 108 int f = (int) Math.ceil(((float) members) / ((float) this.memberToThreadRatio)); 109 Thread [] tmp = new Thread [f]; 110 for (i = 0; i < f; i++) { 111 tmp[i] = this.threads[i]; 112 } 113 for (; i < this.threads.length; i++) { 114 this.threads[i] = null; 115 } 116 this.threads = tmp; 117 } 118 } 119 120 124 public void ratio(int i) { 125 this.memberToThreadRatio = i; 126 } 127 128 129 public synchronized void addAJob(AbstractProcessForGroup r) { 130 this.controler.jobStart(); 131 this.pendingJobs.add(r); 132 this.notify(); 133 } 134 135 138 public synchronized Runnable getJobForThePendingQueue() { 139 try { 140 while (!this.pendingJobs.iterator().hasNext()) { 141 this.wait(); 142 } 143 Runnable r = (Runnable ) this.pendingJobs.iterator().next(); 144 this.pendingJobs.remove(r); 145 return r; 146 } catch (InterruptedException e) { 147 this.controler.jobFinish(); 148 return null; 149 } 150 } 151 152 153 public void complete() { 154 this.controler.waitDone(); 156 } 157 158 159 public void finalize() { 160 this.controler.reset(); 161 for (int i = 0; i < threads.length; i++) { 162 this.threads[i].interrupt(); 163 this.controler.jobStart(); 164 this.threads[i].destroy(); 165 } 166 this.controler.waitDone(); 167 } 168 } 169 | Popular Tags |