这里我们自己动手实现 CoutDownLatch,使用LockSupport 和 等待队列, 如何无法理解,可以学习 《ReentrantLock 的实现》
package com.john.learn.high.concurent.ch03.tools;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;
public class CountDownLatch {
private AtomicInteger count;
private int _startCount;
//挂起线程Queue
private ConcurrentLinkedQueue<Thread> threadQueue = new ConcurrentLinkedQueue<Thread>();
public CountDownLatch(int count) {
this.count = new AtomicInteger(count);
_startCount = count;
}
public void await() throws InterruptedException {
//如果完成,不用park当前线程
if (this.count.get() == 0) {
return;
}
//当前Thread加入Queue
threadQueue.add(Thread.currentThread());
//然后挂起线程
LockSupport.park(this);
if (Thread.interrupted()) {
throw new InterruptedException();
}
}
public void countDown() {
int _count = count.decrementAndGet();
//如果所有线程完成工作,激活park的线程。
if (_count == 0) {
Thread thread = null;
while ((thread = threadQueue.poll()) != null) {
if (thread.isInterrupted() || !thread.isAlive()) {
continue;
}
LockSupport.unpark(thread);
}
}
}
public int getCount() {
return _startCount;
}
}