1 7 8 package java.util.concurrent; 9 import java.util.concurrent.locks.*; 10 import java.util.concurrent.atomic.*; 11 12 126 public class CountDownLatch { 127 131 private static final class Sync extends AbstractQueuedSynchronizer { 132 Sync(int count) { 133 setState(count); 134 } 135 136 int getCount() { 137 return getState(); 138 } 139 140 public int tryAcquireShared(int acquires) { 141 return getState() == 0? 1 : -1; 142 } 143 144 public boolean tryReleaseShared(int releases) { 145 for (;;) { 147 int c = getState(); 148 if (c == 0) 149 return false; 150 int nextc = c-1; 151 if (compareAndSetState(c, nextc)) 152 return nextc == 0; 153 } 154 } 155 } 156 157 private final Sync sync; 158 167 public CountDownLatch(int count) { 168 if (count < 0) throw new IllegalArgumentException ("count < 0"); 169 this.sync = new Sync(count); 170 } 171 172 198 public void await() throws InterruptedException { 199 sync.acquireSharedInterruptibly(1); 200 } 201 202 243 public boolean await(long timeout, TimeUnit unit) 244 throws InterruptedException { 245 return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); 246 } 247 248 257 public void countDown() { 258 sync.releaseShared(1); 259 } 260 261 266 public long getCount() { 267 return sync.getCount(); 268 } 269 270 277 public String toString() { 278 return super.toString() + "[Count = " + sync.getCount() + "]"; 279 } 280 281 } 282 | Popular Tags |