为了加上对CountDownLatch的理解,自己DIY使用synchronized、notifyAll、wait实现CountDownLatch的功能,下面直接贴代码了。如有问题,欢迎大家指出
public class CountDownLatchDiyTest {
public static void main(String[] args) throws Exception {
int n = 1000;
final CountDownLatchDiy startSignal = new CountDownLatchDiy(1);
final CountDownLatchDiy doneSignal = new CountDownLatchDiy(n);
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(100);
for (int i = 0; i < n; i++) {
fixedThreadPool.execute(
new Thread("任务" + String.valueOf(i)) {
public void run() {
try {
startSignal.await();
System.out.println(this.getName() + " thread start");
Thread.sleep(random(100));
System.out.println(this.getName() + " thread over");
doneSignal.countDown();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
System.out.println("main thread start");
startSignal.countDown();
Thread.sleep(random(100));
doneSignal.await();
System.out.println("main thread over");
fixedThreadPool.shutdown();
}
static class CountDownLatchDiy {
private int count;
CountDownLatchDiy(int c) {
this.count = c;
}
public synchronized void countDown() {
if (count > 0) {
count = count - 1;
notifyAll();
return;
}
throw new RuntimeException(Thread.currentThread().getName() + " count <= 0 .");
}
public synchronized void await() throws InterruptedException {
while (count > 0) {
wait();
}
}
}
static long random(long max) {
return 1 + new Double(Math.random() * max).longValue();
}
}