目录
Semaphore
计数信号量(Counting Semaphore)用来控制同时访问某个特定资源的操作数量,或者执行某个指定操作的数量。计数信号量还可以用来实现某种资源池或者对容器进行加边界
Semaphore 中管理着一组虚拟的许可(permit),许可的初始化数量可以通过构造函数来指定。在执行操作时可以首先获取许可(只要还有剩余的许可),并在使用后释放许可(permit)。 如果没有许可(permit)那么aquire将阻塞直到有许可或者直到被中断、操作超时。release方法将释放一个许可,返回给信号量(semaphore)
使用示例
使用信号量实现一个有界的hashSet
public class BoundedHashSet<T> {
//
private final Set<T> set;
// 信号量
private final Semaphore sem;
public BoundedHashSet(int bound) {
//初始化一个同步Set
this.set = Collections.synchronizedSet(new HashSet<T>());
//初始化信号量大小
sem = new Semaphore(bound);
}
public boolean add(T o) throws InterruptedException {
// 获取许可
sem.acquire();
System.out.println("获取许可 " + sem.availablePermits());
boolean wasAdded = false;
try {
wasAdded = set.add(o);
return wasAdded;
} finally {
if (!wasAdded) {
// 如果增加失败
System.out.println("添加失败,释放许可");
sem.release();
}
}
}
public boolean remove(Object o) {
boolean wasRemoved = set.remove(o);
if (wasRemoved) {
// 删除后释放许可
System.out.println("删除成功,释放许可");
sem.release();
}
return wasRemoved;
}
}
CyclicBarrier
我们可以通过闭锁(CountDownLatch)来同时启动一组相关线程,或等待一组相关线程的结束。可是闭锁是一次性对象,一旦进入终止状态,就不能被重置。栅栏类似于闭锁,它能够阻塞一组线程直到某个事件发生。CyclicBarrier可以使一定数量的参与线程反复地在栅栏处汇集。如果希望创建一组任务,并行地执行工作,然后在下一步开始前等待;知道直到所有工作结束。这个就可以使用栅栏(CyclicBarrier)
CyclicBarrier在并行迭代算法中是非常有用的:这种算法将一个问题拆分为一系列相对独立的子问题。当线程到达栅栏位置时将调用await方法,这个方法将阻塞直到所有线程都到达栅栏位置。如果所有线程都到达栅栏位置,那么栅栏将打开,此时所有线程被被释放,而栅栏被重置以便下次使用。如果对await调用超时或者await阻塞线程被中断,那么栅栏就被认为是打破了,所有阻塞的await调用都将抛出一个BrokenBarrierException.
代码示例
假如我们有一个汽车竞速赛事,同时启动最先到达终点的汽车胜出。赛事里程是固定的,我们可以将时间分割成很小的一段,每辆汽车在这一段时间行驶的里程是不同的。
/**
*
* @author zhangwei_david
* @version $Id: Horser.java, v 0.1 2015年7月3日 下午3:15:40 zhangwei_david Exp $
*/
public class Car implements Runnable {
/**
* 汽车ID
*/
private final String id;
/**
* 门闸
*/
private static CyclicBarrier cyclicBarrier;
/**
* 里程
*/
private AtomicInteger strides = new AtomicInteger(0);
private static Random rand = new Random(47);
public Car(CyclicBarrier barrier, String id) {
cyclicBarrier = barrier;
this.id = id;
}
public int getStrides() {
return strides.get();
}
/**
* @see java.lang.Runnable#run()
*/
public void run() {
try {
while (!Thread.interrupted()) {
synchronized (this) {
strides.set(strides.get() + rand.nextInt(3));
}
// 准备了可以开始,当门闸所有的线程都已经调用了await方法则可以继续执行
cyclicBarrier.await();
}
} catch (InterruptedException e) {
} catch (BrokenBarrierException be) {
throw new RuntimeException(be);
}
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return " [car " + id + "]";
}
public String tracks() {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < getStrides(); i++) {
sb.append("-");
}
sb.append(id);
return sb.toString();
}
}
/**
* 汽车拉力赛的类
*
* @author zhangwei_david
* @version $Id: HorseRace.java, v 0.1 2015年7月3日 下午10:27:44 zhangwei_david Exp $
*/
public class CarRace {
/**
* 指定赛道长度
*/
private static final int FINISH_LINE = 75;
/**
* 赛道标尺线
*/
public static final String TRACK = "===========================================================================";
/**
* 参赛汽车
*/
private List<Car> cars = new ArrayList<Car>();
private ExecutorService service = Executors.newCachedThreadPool();
/**
* 门闸
*/
private CyclicBarrier barrier;
public CarRace(int nCars) {
/**
* 创建一个执行线程数量的CyclicBarrier,当所有现在都准备好以后则CyclicBarrier可以开闸放行,此时回调给定的barrierAction
*
*/
barrier = new CyclicBarrier(nCars, new Runnable() {
public void run() {
printEvent();
judge();
try {
TimeUnit.MILLISECONDS.sleep(200);
} catch (Exception e) {
}
}
/**
* 裁判
*/
private void judge() {
for (Car car : cars) {
if (car.getStrides() >= FINISH_LINE) {
System.out.println(car + " won!");
service.shutdownNow();
return;
}
}
}
/**
* 赛事实况
*/
private void printEvent() {
System.out.println(TRACK);
for (Car car : cars) {
System.out.println(car.tracks());
}
System.out.println(TRACK);
}
});
for (int i = 0; i < nCars; i++) {
Car car = new Car(barrier, String.valueOf(i));
cars.add(car);
service.execute(car);
}
}
public static void main(String[] args) {
new CarRace(7);
}
}
执行结果:
===========================================================================
--0
--1
-2
--3
-4
--5
-6
===========================================================================
===========================================================================
---0
--1
--2
--3
-4
--5
---6
===========================================================================
===========================================================================
----0
---1
----2
----3
--4
---5
----6
===========================================================================
===========================================================================
----0
-----1
-----2
------3
---4
---5
----6
===========================================================================
===========================================================================
----0
------1
------2
-------3
----4
-----5
----6
===========================================================================
===========================================================================
----0
------1
-------2
---------3
-----4
-----5
----6
===========================================================================
===========================================================================
-----0
--------1
--------2
---------3
-----4
------5
-----6
===========================================================================
===========================================================================
-------0
---------1
----------2
----------3
------4
------5
------6
===========================================================================
===========================================================================
-------0
---------1
------------2
-----------3
------4
------5
------6
===========================================================================
===========================================================================
-------0
-----------1
------------2
------------3
--------4
-------5
-------6
===========================================================================
===========================================================================
-------0
-------------1
------------2
--------------3
--------4
-------5
--------6
===========================================================================
===========================================================================
---------0
---------------1
-------------2
---------------3
----------4
-------5
----------6
===========================================================================
===========================================================================
-----------0
---------------1
--------------2
---------------3
----------4
--------5
------------6
===========================================================================
===========================================================================
------------0
----------------1
----------------2
---------------3
------------4
--------5
------------6
===========================================================================
===========================================================================
------------0
----------------1
------------------2
---------------3
-------------4
--------5
--------------6
===========================================================================
===========================================================================
--------------0
-----------------1
--------------------2
---------------3
---------------4
---------5
--------------6
===========================================================================
===========================================================================
----------------0
-------------------1
---------------------2
----------------3
-----------------4
---------5
---------------6
===========================================================================
===========================================================================
-----------------0
--------------------1
---------------------2
----------------3
-----------------4
-----------5
----------------6
===========================================================================
===========================================================================
-------------------0
--------------------1
----------------------2
----------------3
-----------------4
-------------5
----------------6
===========================================================================
===========================================================================
---------------------0
---------------------1
----------------------2
------------------3
-----------------4
---------------5
-----------------6
===========================================================================
===========================================================================
----------------------0
---------------------1
----------------------2
--------------------3
-------------------4
-----------------5
-------------------6
===========================================================================
===========================================================================
-----------------------0
----------------------1
----------------------2
----------------------3
-------------------4
-------------------5
---------------------6
===========================================================================
===========================================================================
------------------------0
----------------------1
------------------------2
-----------------------3
--------------------4
-------------------5
-----------------------6
===========================================================================
===========================================================================
--------------------------0
----------------------1
--------------------------2
-------------------------3
--------------------4
-------------------5
-------------------------6
===========================================================================
===========================================================================
--------------------------0
----------------------1
---------------------------2
---------------------------3
--------------------4
--------------------5
-------------------------6
===========================================================================
===========================================================================
---------------------------0
------------------------1
-----------------------------2
---------------------------3
---------------------4
---------------------5
--------------------------6
===========================================================================
===========================================================================
---------------------------0
-------------------------1
-------------------------------2
---------------------------3
----------------------4
---------------------5
----------------------------6
===========================================================================
===========================================================================
-----------------------------0
--------------------------1
-------------------------------2
---------------------------3
-----------------------4
----------------------5
------------------------------6
===========================================================================
===========================================================================
------------------------------0
--------------------------1
--------------------------------2
-----------------------------3
------------------------4
----------------------5
--------------------------------6
===========================================================================
===========================================================================
-------------------------------0
---------------------------1
----------------------------------2
-------------------------------3
--------------------------4
----------------------5
---------------------------------6
===========================================================================
===========================================================================
-------------------------------0
---------------------------1
----------------------------------2
---------------------------------3
--------------------------4
------------------------5
-----------------------------------6
===========================================================================
===========================================================================
---------------------------------0
----------------------------1
-----------------------------------2
----------------------------------3
---------------------------4
------------------------5
-----------------------------------6
===========================================================================
===========================================================================
-----------------------------------0
----------------------------1
-------------------------------------2
----------------------------------3
---------------------------4
-------------------------5
-----------------------------------6
===========================================================================
===========================================================================
-----------------------------------0
------------------------------1
---------------------------------------2
-----------------------------------3
---------------------------4
---------------------------5
-------------------------------------6
===========================================================================
===========================================================================
-----------------------------------0
------------------------------1
----------------------------------------2
------------------------------------3
---------------------------4
-----------------------------5
-------------------------------------6
===========================================================================
===========================================================================
-----------------------------------0
-------------------------------1
------------------------------------------2
------------------------------------3
---------------------------4
-----------------------------5
-------------------------------------6
===========================================================================
===========================================================================
-------------------------------------0
--------------------------------1
------------------------------------------2
-------------------------------------3
---------------------------4
-----------------------------5
---------------------------------------6
===========================================================================
===========================================================================
--------------------------------------0
----------------------------------1
------------------------------------------2
---------------------------------------3
---------------------------4
------------------------------5
---------------------------------------6
===========================================================================
===========================================================================
----------------------------------------0
------------------------------------1
--------------------------------------------2
---------------------------------------3
-----------------------------4
-------------------------------5
----------------------------------------6
===========================================================================
===========================================================================
----------------------------------------0
--------------------------------------1
----------------------------------------------2
----------------------------------------3
-------------------------------4
-------------------------------5
-----------------------------------------6
===========================================================================
===========================================================================
----------------------------------------0
---------------------------------------1
-----------------------------------------------2
-----------------------------------------3
-------------------------------4
---------------------------------5
-------------------------------------------6
===========================================================================
===========================================================================
-----------------------------------------0
-----------------------------------------1
------------------------------------------------2
------------------------------------------3
-------------------------------4
-----------------------------------5
---------------------------------------------6
===========================================================================
===========================================================================
------------------------------------------0
-------------------------------------------1
------------------------------------------------2
-------------------------------------------3
---------------------------------4
------------------------------------5
---------------------------------------------6
===========================================================================
===========================================================================
--------------------------------------------0
-------------------------------------------1
------------------------------------------------2
-------------------------------------------3
---------------------------------4
------------------------------------5
-----------------------------------------------6
===========================================================================
===========================================================================
--------------------------------------------0
---------------------------------------------1
--------------------------------------------------2
-------------------------------------------3
-----------------------------------4
-------------------------------------5
-------------------------------------------------6
===========================================================================
===========================================================================
----------------------------------------------0
----------------------------------------------1
--------------------------------------------------2
-------------------------------------------3
-------------------------------------4
-------------------------------------5
--------------------------------------------------6
===========================================================================
===========================================================================
------------------------------------------------0
-----------------------------------------------1
---------------------------------------------------2
---------------------------------------------3
---------------------------------------4
--------------------------------------5
----------------------------------------------------6
===========================================================================
===========================================================================
-------------------------------------------------0
------------------------------------------------1
-----------------------------------------------------2
---------------------------------------------3
----------------------------------------4
----------------------------------------5
-----------------------------------------------------6
===========================================================================
===========================================================================
---------------------------------------------------0
--------------------------------------------------1
------------------------------------------------------2
----------------------------------------------3
----------------------------------------4
-----------------------------------------5
-------------------------------------------------------6
===========================================================================
===========================================================================
----------------------------------------------------0
---------------------------------------------------1
--------------------------------------------------------2
------------------------------------------------3
------------------------------------------4
------------------------------------------5
--------------------------------------------------------6
===========================================================================
===========================================================================
------------------------------------------------------0
-----------------------------------------------------1
----------------------------------------------------------2
------------------------------------------------3
------------------------------------------4
------------------------------------------5
----------------------------------------------------------6
===========================================================================
===========================================================================
------------------------------------------------------0
-------------------------------------------------------1
-----------------------------------------------------------2
------------------------------------------------3
------------------------------------------4
------------------------------------------5
------------------------------------------------------------6
===========================================================================
===========================================================================
------------------------------------------------------0
--------------------------------------------------------1
------------------------------------------------------------2
------------------------------------------------3
-------------------------------------------4
-------------------------------------------5
-------------------------------------------------------------6
===========================================================================
===========================================================================
------------------------------------------------------0
---------------------------------------------------------1
------------------------------------------------------------2
--------------------------------------------------3
-------------------------------------------4
---------------------------------------------5
--------------------------------------------------------------6
===========================================================================
===========================================================================
-------------------------------------------------------0
----------------------------------------------------------1
------------------------------------------------------------2
----------------------------------------------------3
---------------------------------------------4
-----------------------------------------------5
--------------------------------------------------------------6
===========================================================================
===========================================================================
--------------------------------------------------------0
------------------------------------------------------------1
------------------------------------------------------------2
------------------------------------------------------3
---------------------------------------------4
-------------------------------------------------5
---------------------------------------------------------------6
===========================================================================
===========================================================================
----------------------------------------------------------0
--------------------------------------------------------------1
-------------------------------------------------------------2
------------------------------------------------------3
-----------------------------------------------4
---------------------------------------------------5
----------------------------------------------------------------6
===========================================================================
===========================================================================
-----------------------------------------------------------0
----------------------------------------------------------------1
---------------------------------------------------------------2
------------------------------------------------------3
-----------------------------------------------4
-----------------------------------------------------5
------------------------------------------------------------------6
===========================================================================
===========================================================================
-------------------------------------------------------------0
-----------------------------------------------------------------1
---------------------------------------------------------------2
------------------------------------------------------3
-----------------------------------------------4
-----------------------------------------------------5
-------------------------------------------------------------------6
===========================================================================
===========================================================================
-------------------------------------------------------------0
-------------------------------------------------------------------1
---------------------------------------------------------------2
-------------------------------------------------------3
-------------------------------------------------4
-------------------------------------------------------5
--------------------------------------------------------------------6
===========================================================================
===========================================================================
---------------------------------------------------------------0
-------------------------------------------------------------------1
-----------------------------------------------------------------2
--------------------------------------------------------3
--------------------------------------------------4
-------------------------------------------------------5
--------------------------------------------------------------------6
===========================================================================
===========================================================================
---------------------------------------------------------------0
-------------------------------------------------------------------1
-----------------------------------------------------------------2
---------------------------------------------------------3
----------------------------------------------------4
--------------------------------------------------------5
----------------------------------------------------------------------6
===========================================================================
===========================================================================
-----------------------------------------------------------------0
-------------------------------------------------------------------1
-----------------------------------------------------------------2
----------------------------------------------------------3
-----------------------------------------------------4
--------------------------------------------------------5
------------------------------------------------------------------------6
===========================================================================
===========================================================================
------------------------------------------------------------------0
--------------------------------------------------------------------1
-------------------------------------------------------------------2
-----------------------------------------------------------3
-------------------------------------------------------4
---------------------------------------------------------5
--------------------------------------------------------------------------6
===========================================================================
===========================================================================
-------------------------------------------------------------------0
----------------------------------------------------------------------1
-------------------------------------------------------------------2
-----------------------------------------------------------3
--------------------------------------------------------4
---------------------------------------------------------5
--------------------------------------------------------------------------6
===========================================================================
===========================================================================
-------------------------------------------------------------------0
-----------------------------------------------------------------------1
--------------------------------------------------------------------2
-------------------------------------------------------------3
----------------------------------------------------------4
---------------------------------------------------------5
---------------------------------------------------------------------------6
===========================================================================
[car 6] won!
源码分析
public class CyclicBarrier {
private static class Generation {
boolean broken = false;
}
/** 栅栏入口的锁 */
private final ReentrantLock lock = new ReentrantLock();
/** 一直等待到跳闸的条件 */
private final Condition trip = lock.newCondition();
/** 缔约方数量 */
private final int parties;
/*跳闸时执行的命令 */
private final Runnable barrierCommand;
private Generation generation = new Generation();
/**
* 尚未等待的缔约方数量
*/
private int count;
/**
* 获取下一代
*/
private void nextGeneration() {
trip.signalAll();
count = parties;
generation = new Generation();
}
/**
* 设置当前栅栏代被打破,唤醒所有等待线程
*/
private void breakBarrier() {
generation.broken = true;
count = parties;
trip.signalAll();
}
/**
* Main barrier code, covering the various policies.
*/
private int dowait(boolean timed, long nanos)
throws InterruptedException, BrokenBarrierException,
TimeoutException {
//重入锁
final ReentrantLock lock = this.lock;
// 锁
lock.lock();
try {
final Generation g = generation;
// 如果当前一代栅栏已经跳闸则抛出异常
if (g.broken)
throw new BrokenBarrierException();
// 如果线程中断则打开栅栏
if (Thread.interrupted()) {
breakBarrier();
throw new InterruptedException();
}
// 等待线程自减
int index = --count;
// 如果当前线程已经是最后一个线程,则执行回调同时代开栅栏
if (index == 0) { // tripped
boolean ranAction = false;
try {
final Runnable command = barrierCommand;
if (command != null)
command.run();
ranAction = true;
nextGeneration();
return 0;
} finally {
if (!ranAction)
breakBarrier();
}
}
// 一直循环直到栅栏跳闸,打开,中断或超时
for (;;) {
try {
if (!timed)
trip.await();
else if (nanos > 0L)
nanos = trip.awaitNanos(nanos);
} catch (InterruptedException ie) {
if (g == generation && ! g.broken) {
breakBarrier();
throw ie;
} else {
Thread.currentThread().interrupt();
}
}
if (g.broken)
throw new BrokenBarrierException();
if (g != generation)
return index;
if (timed && nanos <= 0L) {
breakBarrier();
throw new TimeoutException();
}
}
} finally {
lock.unlock();
}
}
/**
* 创建一个新的CyclicBarrier,他会在指定数量的线程都在等待是跳闸,最后一个线程通过栅栏后执行栅栏回调处理
*/
public CyclicBarrier(int parties, Runnable barrierAction) {
if (parties <= 0) throw new IllegalArgumentException();
// 缔约方数量是指定的线程数
this.parties = parties;
//等待线程数
this.count = parties;
//栅栏命令
this.barrierCommand = barrierAction;
}
/**
*/
public CyclicBarrier(int parties) {
this(parties, null);
}
/**
* 获取缔约方数量
*/
public int getParties() {
return parties;
}
/**
* 一直阻塞到所有的缔约方都调用这个方法
*/
public int await() throws InterruptedException, BrokenBarrierException {
try {
return dowait(false, 0L);
} catch (TimeoutException toe) {
throw new Error(toe); // cannot happen
}
}
public int await(long timeout, TimeUnit unit)
throws InterruptedException,
BrokenBarrierException,
TimeoutException {
return dowait(true, unit.toNanos(timeout));
}
/**
* 查询当前栅栏是否被打破
*/
public boolean isBroken() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return generation.broken;
} finally {
lock.unlock();
}
}
/**
* 重置栅栏
*/
public void reset() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
breakBarrier(); // break the current generation
nextGeneration(); // start a new generation
} finally {
lock.unlock();
}
}
/**
* 获取等待的线程数量
*/
public int getNumberWaiting() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return parties - count;
} finally {
lock.unlock();
}
}
}
CountDownLatch
实现并发的最直接方式是在操作系统级别使用进程。进程是运行在自己的地址空间内的自包容程序。多任务操作系统可以通过周期性地将CPU从一个进程切换到另一个进程,来实现同时运行多个进程的。操作系统将进程相互隔离开,因此他们不会相互干扰,这使得通过进程实现并发编程相对容易一些。而JAVA的并发时通过多线程机制实现的。
一个线程就是在进程中的一个单一的顺序控制流,因此,单个进程可以拥有多个并发执行的任务,使得程序看起来好像都有其自己的CPU一样。其底层的机制是切分CPU的时间片。
java.util.concurrency包提供了很多并发编程的工具类,可以极大提高并发编程的效率。
闭锁是一种同步工具类,可以延迟线程的进度直到闭锁到达终止状态。Latch在英语中就是门栓的意思,所以形象地说闭锁就相当于一扇门,在日常生 活中我们都遇到过类似的场景,进入一个场馆前,必须达到一定的条件,比如活动开始前半小时可以入场;如果来早了的话,对不起,以便等着。 CountDownLatch 在多线程中也是这样的作用,在闭锁到达结束状态前,这扇门是一直关闭的,不允许任何线程通过,当到达结束状态时,这扇门就 保持打开,并且是永久的处于打开状态;也就是说这个门是一次性的。 如同柏林墙一样,推到了就建不起来了。
闭锁可以用来确保某些活动直到其他活动都完成后才继续执行。CountDownLatch是一种灵活的闭锁实现,它可以使一个或多个线程 等待一组事件的发生。闭锁包括一个计数器,该计数器被初始化为一个正整数,表示等待的事件数量。有一等待时间发生时,使用countDown方法递减计数 器,而await方法就是等待所有事件的发生,也就是计数器的值为0.如果计数器的值不为0 那么await 方法需要一直等待
示例代码
这是一个赛马场景,比赛开始所有马匹进入赛道;当所有马匹都准备就绪后就同时开闸比赛,当所有马匹到达终点后进行本场比赛统计。代码如下
/**
*
* @author zhangwei_david
* @version $Id: TestHarness.java, v 0.1 2014年11月10日 下午5:08:17 zhangwei_david Exp $
*/
public class TestHarness {
public long timeTasks(int nThreads, final Runnable task) throws InterruptedException {
// 定义开门的闭锁
final CountDownLatch startGate = new CountDownLatch(1);
// 定义关门的闭锁对象,
final CountDownLatch endGate = new CountDownLatch(nThreads);
for (int i = 0; i < nThreads; i++) {
Thread t = new Thread() {
@Override
public void run() {
try {
// 等待所有线程都准备好
startGate.await();
try {
task.run();
} finally {
// 线程执行结束,闭锁减一
endGate.countDown();
}
} catch (InterruptedException e1) {
}
}
};
t.start();
}
long start = System.nanoTime();
所有的线程都准备好,可以执行
startGate.countDown();
// 等待所有线程执行结束
endGate.await();
long end = System.nanoTime();
return end - start;
}
}
/**
*
* @author zhangwei_david
* @version $Id: Test.java, v 0.1 2014年11月10日 下午5:13:24 zhangwei_david Exp $
*/
public class Test {
public static void main(String[] args) throws InterruptedException {
System.out.println(new TestHarness().timeTasks(10, new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName() + "开始执行时间:"
+ System.currentTimeMillis());
}
}));
}
}
测试结果:
Thread-2开始执行时间:1435904413836
Thread-9开始执行时间:1435904413836
Thread-5开始执行时间:1435904413836
Thread-7开始执行时间:1435904413836
Thread-6开始执行时间:1435904413836
Thread-3开始执行时间:1435904413836
Thread-8开始执行时间:1435904413836
Thread-1开始执行时间:1435904413836
Thread-0开始执行时间:1435904413836
Thread-4开始执行时间:1435904413836
源码分析
public class CountDownLatch {
/**
* 闭锁的同步控制类
*/
private static final class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 4982264981922014374L;
//
Sync(int count) {
setState(count);
}
int getCount() {
return getState();
}
//获取共享锁,如果当前线程数量为0则表示获取到锁,否则无法获取
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 CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
/**
* 当前线程一直等到闭锁的数量为0才可以执行
*/
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
/**
* 当前线程等到闭锁的数量为0或者超时
*/
public boolean await(long timeout, TimeUnit unit)
throws InterruptedException {
return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}
/**
* 闭锁减去1
*/
public void countDown() {
sync.releaseShared(1);
}
/**
* 获取当前闭锁的数量
*/
public long getCount() {
return sync.getCount();
}
public String toString() {
return super.toString() + "[Count = " + sync.getCount() + "]";
}
}