1 13 14 package EDU.oswego.cs.dl.util.concurrent; 15 16 128 129 public class CondVar { 130 131 132 protected final Sync mutex_; 133 134 148 149 public CondVar(Sync mutex) { 150 mutex_ = mutex; 151 } 152 153 164 public void await() throws InterruptedException { 165 if (Thread.interrupted()) throw new InterruptedException (); 166 try { 167 synchronized(this) { 168 mutex_.release(); 169 try { 170 wait(); 171 } 172 catch (InterruptedException ex) { 173 notify(); 174 throw ex; 175 } 176 } 177 } 178 finally { 179 boolean interrupted = false; 181 for (;;) { 182 try { 183 mutex_.acquire(); 184 break; 185 } 186 catch (InterruptedException ex) { 187 interrupted = true; 188 } 189 } 190 if (interrupted) { 191 Thread.currentThread().interrupt(); 192 } 193 } 194 } 195 196 212 213 public boolean timedwait(long msecs) throws InterruptedException { 214 if (Thread.interrupted()) throw new InterruptedException (); 215 boolean success = false; 216 try { 217 synchronized(this) { 218 mutex_.release(); 219 try { 220 if (msecs > 0) { 221 long start = System.currentTimeMillis(); 222 wait(msecs); 223 success = System.currentTimeMillis() - start <= msecs; 224 } 225 } 226 catch (InterruptedException ex) { 227 notify(); 228 throw ex; 229 } 230 } 231 } 232 finally { 233 boolean interrupted = false; 235 for (;;) { 236 try { 237 mutex_.acquire(); 238 break; 239 } 240 catch (InterruptedException ex) { 241 interrupted = true; 242 } 243 } 244 if (interrupted) { 245 Thread.currentThread().interrupt(); 246 } 247 } 248 return success; 249 } 250 251 256 public synchronized void signal() { 257 notify(); 258 } 259 260 261 public synchronized void broadcast() { 262 notifyAll(); 263 } 264 } 265 | Popular Tags |