相关阅读
- JUC源码简析 AbstractQueuedSynchronizer
- JUC源码简析 Condition
- JUC源码简析 CyclicBarrier
- JUC源码简析 ReentrantLock
- JUC源码简析 Semaphore
简介
可以使一个线程等待其它线程执行完相应任务后再执行的同步器;
内部维护一个计数器,计数器的初始值表示需要调用countDown
方法的次数(一般每个等待线程调用一次countDown
方法,也就表示等待线程的数量),每一个等待的线程执行完相应的任务后,调用countDown
方法将计数器的值减一,当计数器的值为0时,表示所有等待线程的任务已经执行完成,那么在此同步器上等待的线程就可以继续下一步动作了;
不足
- 只能使用一次,无法重复使用;
源码简析
内部类——Sync
简介
继承自AbstractQueuedSynchronizer
,重写了父类的tryAcquireShared
、tryReleaseShared
方法;
getCount
int getCount() {
// 返回当前的锁资源状态
return getState();
}
tryAcquireShared
protected int tryAcquireShared(int acquires) {
// 如果当前资源状态为0,则表示所有等待线程都完成了相应任务并执行了countDown
// 那么返回1,表示本线程获取锁成功
// 否则返回-1,表示获取锁失败
return (getState() == 0) ? 1 : -1;
}
tryReleaseShared
protected boolean tryReleaseShared(int releases) {
// Decrement count; signal when transition to zero
// 死循环保证释放锁成功若存在共享锁资源的话,存在多线程同时修改共享锁资源状态
for (;;) {
int c = getState();
if (c == 0)
// 如果当前锁状态已经为0,无资源可释放,则返回false
return false;
int nextc = c-1;
// CAS尝试更新锁资源
// 更新失败,存在其它线程同时尝试释放锁,那么需要进行下一循环
if (compareAndSetState(c, nextc))
// 更新成功,则返回当前锁状态
// 当前锁状态为0,则返回true,表示共享锁释放成功
// 当前锁状态不为0,则表示还存在线程未执行countDown,返回false表示共享锁还未释放成功
return nextc == 0;
}
}
CountDownLatch
简介
CountDownLatch
提供的接口均是通过内部类Sync
实现;
构造方法
public CountDownLatch(int count) {
// 校验锁资源状态初始值,必须不小于0,等于0,则表示不需要等待任何线程
if (count < 0) throw new IllegalArgumentException("count < 0");
// 设置初始锁资源状态
this.sync = new Sync(count);
}
await
public void await() throws InterruptedException {
// 等待获取共享锁,支持中断
sync.acquireSharedInterruptibly(1);
}
public boolean await(long timeout, TimeUnit unit)
throws InterruptedException {
// 等待获取共享锁,支持超时时间
return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}
countDown
public void countDown() {
// 释放共享锁
sync.releaseShared(1);
}
getCount
public long getCount() {
// 返回当前的锁资源状态
return sync.getCount();
}
测试
Demo
class Demo {
private int parties = 5;
private CountDownLatch latch = new CountDownLatch(parties);
public static void main(String[] args) throws InterruptedException {
Demo demo = new Demo();
ExecutorService es = Executors.newFixedThreadPool(demo.parties);
for (int i=0; i<demo.parties; i++) {
es.execute(new CountDownLatchTask(i, demo.latch));
}
System.out.println("Main is awaiting");
demo.latch.await();
System.out.println("Main finishes");
es.shutdown();
}
private static class CountDownLatchTask implements Runnable {
private CountDownLatch latch;
private int index;
CountDownLatchTask(int index, CountDownLatch latch) {
this.latch = latch;
this.index = index;
}
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(2);
System.out.println("Thread:" + index + " has done");
latch.countDown();
TimeUnit.SECONDS.sleep(2);
System.out.println("Thread:" + index + " has exited");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
测试结果
Main is awaiting
Thread:0 has done
Thread:3 has done
Thread:4 has done
Thread:2 has done
Thread:1 has done
Main finishes
Thread:0 has exited
Thread:4 has exited
Thread:1 has exited
Thread:3 has exited
Thread:2 has exited