使用例子
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
public class Main {
private static CountDownLatch startGate = new CountDownLatch(1);
private static CountDownLatch endGate = new CountDownLatch(10);
public static void main(String[] args) throws IOException, InterruptedException {
Runnable task = new Runnable() {
@Override
public void run() {
System.out.println("this is a test");
}
};
for (int i = 0; i < 10; i++) {
Thread thread = new Thread() {
@Override
public void run() {
try {
startGate.await();
task.run();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
endGate.countDown();
}
}
};
thread.start();
}
long start = System.nanoTime();
startGate.countDown();
endGate.await();
long end = System.nanoTime();
System.out.println(end - start);
}
}
源码分析
private static final class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 4982264981922014374L;
Sync(int count) {
setState(count);
}
int getCount() {
return getState();
}
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1;
}
protected boolean tryReleaseShared(int releases) {
for (;;) {
int c = getState();
if (c == 0)
return false;
int nextc = c-1;
if (compareAndSetState(c, nextc))
return nextc == 0;
}
}
}
private final Sync sync;
...
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
public void countDown() {
sync.releaseShared(1);
}
}