CountDownLatch
CountDownLatch
通过计数器实现一个线程等待其他若干线程执行完后,本线程再继续执行的功能。
使用举例
public static void main(String[] args) throws InterruptedException {
//CountDownLatch传入数量n 主线程执行await()后 阻塞等待两个子线程执行
// 当子线程执行完毕时会调用countDown() 此时n会减一 当n减至0时主线程会重新执行
CountDownLatch latch = new CountDownLatch(2);
MyRunnable runnable = new MyRunnable(latch);
Thread thread1 = new Thread(runnable, ThreadConsts.THREAD_1);
Thread thread2 = new Thread(runnable, ThreadConsts.THREAD_2);
thread1.start();
thread2.start();
System.out.println("Main Thread: 开始等待其他线程执行");
latch.await();
System.out.println("Main Thread: 继续执行");
}
static class MyRunnable implements Runnable {
private CountDownLatch latch;
MyRunnable(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":开始执行");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":执行完毕");
latch.countDown();
}
}
执行结果:
Main Thread: 开始等待其他线程执行
线程1:开始执行
线程2:开始执行
线程1:执行完毕
线程2:执行完毕
Main Thread: 继续执行
源码解析
public class CountDownLatch {
private final Sync sync;
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
public boolean await(long timeout, TimeUnit unit)
throws InterruptedException {
return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}
public void countDown() {
sync.releaseShared(1);
}
public long getCount() {
return sync.getCount();
}
public String toString() {
return super.toString() + "[Count = " + sync.getCount() + "]";
}
//静态内部类Sync
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) {
// Decrement count; signal when transition to zero
for (;;) {
int c = getState();
if (c == 0)
return false;
int nextc = c-1;
if (compareAndSetState(c, nextc))
return nextc == 0;
}
}
}
}
CountDownLatch
构造方法初始化了Sync
内部类,本质上是通过AQS
实现的共享锁
Semaphore
Semaphore
翻译为信号量,是一种共享锁。可以同时允许一个或多个线程同时共享资源,Semaphore
的构造参数如下:
public Semaphore(int permits) {
sync = new NonfairSync(permits);
}
public Semaphore(int permits, boolean fair) {
sync = fair ? new FairSync(permits) : new NonfairSync(permits);
}
permits
表示资源的最大访问量,表示最多有Permits
个线程同时访问资源,fair
表示是否是公平锁。Semaphore
使用时的几个主要方法:
public void acquire() //获取一个许可 成功返回true 失败返回false并进入队列等待
public void acquire(int permits) //获取permits个许可
public void release() //释放一个许可
public void release(int permits) //释放permits个许可
使用举例
public static void main(String[] args) throws InterruptedException {
//银行一共有2个柜台 true表示公平锁 false是非公平锁
Semaphore semaphore = new Semaphore(2, true);
//一共有10个顾客来办理业务
for (int i = 0; i < 10; i++) {
Client client = new Client(semaphore, "client" + i);
client.start();
Thread.sleep(10);
}
}
private static class Client extends Thread {
private Semaphore semaphore;
private String threadName;
Client(Semaphore semaphore, String threadName) {
this.semaphore = semaphore;
this.threadName = threadName;
}
@Override
public void run() {
try {
//acquire()获取一次使用权限
semaphore.acquire();
System.out.println(threadName + "开始办理业务,当前可使用许可数(空闲柜台数):" + semaphore.availablePermits());
Thread.sleep(1000);
//release释放一次使用权限
semaphore.release();
System.out.println("==>" + threadName + "结束办理业务,当前可使用许可数(空闲柜台数):" + semaphore.availablePermits());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
执行结果:
client0开始办理业务,当前可使用许可数(空闲柜台数):1
client1开始办理业务,当前可使用许可数(空闲柜台数):0
==>client0结束办理业务,当前可使用许可数(空闲柜台数):1
client2开始办理业务,当前可使用许可数(空闲柜台数):0
==>client1结束办理业务,当前可使用许可数(空闲柜台数):1
client3开始办理业务,当前可使用许可数(空闲柜台数):0
==>client2结束办理业务,当前可使用许可数(空闲柜台数):1
client4开始办理业务,当前可使用许可数(空闲柜台数):0
==>client3结束办理业务,当前可使用许可数(空闲柜台数):1
client5开始办理业务,当前可使用许可数(空闲柜台数):0
==>client4结束办理业务,当前可使用许可数(空闲柜台数):1
client6开始办理业务,当前可使用许可数(空闲柜台数):0
==>client5结束办理业务,当前可使用许可数(空闲柜台数):1
client7开始办理业务,当前可使用许可数(空闲柜台数):0
==>client6结束办理业务,当前可使用许可数(空闲柜台数):0
client8开始办理业务,当前可使用许可数(空闲柜台数):0
==>client7结束办理业务,当前可使用许可数(空闲柜台数):1
client9开始办理业务,当前可使用许可数(空闲柜台数):0
==>client8结束办理业务,当前可使用许可数(空闲柜台数):1
==>client9结束办理业务,当前可使用许可数(空闲柜台数):2
源码解析
public void acquire() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
public void acquire(int permits) throws InterruptedException {
if (permits < 0) throw new IllegalArgumentException();
sync.acquireSharedInterruptibly(permits);
}
public void release(int permits) {
if (permits < 0) throw new IllegalArgumentException();
sync.releaseShared(permits);
}
public void release() {
sync.releaseShared(1);
}
//tryAcquire跟上面的acquire方法一样回去尝试获取锁,不同的是tryAcquire可以立即获取执行结果
public boolean tryAcquire() {
return sync.nonfairTryAcquireShared(1) >= 0;
}
public boolean tryAcquire(long timeout, TimeUnit unit)
throws InterruptedException {
return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}
public boolean tryAcquire(int permits) {
if (permits < 0) throw new IllegalArgumentException();
return sync.nonfairTryAcquireShared(permits) >= 0;
}
public boolean tryAcquire(int permits, long timeout, TimeUnit unit)
throws InterruptedException {
if (permits < 0) throw new IllegalArgumentException();
return sync.tryAcquireSharedNanos(permits, unit.toNanos(timeout));
}
Semaphore
构造方法初始化了Sync
内部类,本质上也是通过AQS
实现的共享锁。
CyclicBarrier
CyclicBarrier
意为循环栅栏,可以实现一组线程等待至某个状态之后再全部继续执行。当所有线程执行完毕后,CyclicBarrier
还可以继续被重用。
使用举例
public static void main(String[] args) {
System.out.println("CyclicBarrier例子:");
//构造方法中传入的Runnable是由最后通过栅栏的线程去执行,如本例中栅栏数声明为3,当最后一个线程执行await()时,最后这个线程会再去执行这里声明的Runnable任务
//这里Runnable是非必须的,不声明的话不会执行,同时CyclicBarrier将允许所有线程继续执行。
CyclicBarrier barrier = new CyclicBarrier(3, new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "是最后一个通过栅栏的线程,它继续执行CyclicBarrier构造方法中的Runnable任务(如有)");
}
});
for (int i = 0; i < 3; i++) {
new Thread(new MyTask(barrier), ThreadConsts.THREAD + i).start();
}
}
static class MyTask implements Runnable {
CyclicBarrier barrier;
MyTask(CyclicBarrier barrier) {
this.barrier = barrier;
}
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + ":开始执行");
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + ":执行完毕,等待其他线程执行");
barrier.await();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println(Thread.currentThread().getName() + ":通过栅栏,所有任务执行完毕");
}
}
}
执行结果:
CyclicBarrier例子:
线程1:开始执行
线程0:开始执行
线程2:开始执行
线程2:执行完毕,等待其他线程执行
线程0:执行完毕,等待其他线程执行
线程1:执行完毕,等待其他线程执行
线程1是最后一个通过栅栏的线程,它继续执行CyclicBarrier构造方法中的Runnable任务(如有)
线程1:通过栅栏,所有任务执行完毕
线程2:通过栅栏,所有任务执行完毕
线程0:通过栅栏,所有任务执行完毕
源码解析
public CyclicBarrier(int parties) {
this(parties, null);
}
public CyclicBarrier(int parties, Runnable barrierAction) {
if (parties <= 0) throw new IllegalArgumentException();
this.parties = parties;
this.count = parties;
this.barrierCommand = barrierAction;
}
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));
}
private int dowait(boolean timed, long nanos)
throws InterruptedException, BrokenBarrierException,
TimeoutException {
final ReentrantLock lock = this.lock;
lock.lock();
try {
final Generation g = generation;
int index = --count;
//1、当index==0时表示所有线程都执行了await操作
if (index == 0) { // tripped
boolean ranAction = false;
try {
//2、如果barrierCommand不为空且index==0,则由最后通过栅栏的线程去执行该barrierCommand
final Runnable command = barrierCommand;
if (command != null)
command.run();
ranAction = true;
nextGeneration();
return 0;
} finally {
if (!ranAction)
breakBarrier();
}
}
// loop until tripped, broken, interrupted, or timed out
for (;;) {
try {
if (!timed)
//3、阻塞等待其他线程去执行
trip.await();
else if (nanos > 0L)
nanos = trip.awaitNanos(nanos);
} catch (InterruptedException ie) { }
}
} finally {
lock.unlock();
}
}
//唤醒所有线程继续执行
private void nextGeneration() {
// signal completion of last generation
trip.signalAll();
// set up next generation
count = parties;
generation = new Generation();
}
总结
CountDownLatch
和 CyclicBarrier
都可以实现线程之间的等待,但是两者的侧重点不同:
CountDownLatch
侧重于一个线程等待其他若干个线程执行完之后,这个线程会在其他线程执行完毕后继续执行该线程。CyclicBarrier
侧重于多个线程互相等待至某个状态,然后这一组线程就会继续同时执行;CountDownLatch
不可复用,CyclicBarrier
可以复用