CountDownLatch :倒计时器,是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程的操作执行完后再执行。
将 CountDownLatch 的计数器初始化为 n :new CountDownLatch(n),每当一个任务线程执行完毕,就将计数器减 1 countdownlatch.countDown(),当计数器的值变为 0 时,在CountDownLatch上 await() 的线程就会被唤醒。一个典型应用场景就是启动一个服务时,主线程需要等待多个组件加载完毕,之后再继续执行。
情况①:设定遍历次数、核心线程数 countdownLatch都为size时,直到等待所有核心线程都执行完成后,再调用主线程的代码
public class CountDownLatchTest {
private static final int size = 8;
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(size);
CountDownLatch countDownLatch = new CountDownLatch(size);
IntStream.range(0,size).forEach(
r-> executorService.execute( () -> {
System.out.println(Thread.currentThread().getName() + " start countDownLatch Test" + r);
try {
Thread.sleep(1000);//模拟耗时操作
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " end countDownLatch Test"+ r);
countDownLatch.countDown();
})
);
executorService.shutdown();
countDownLatch.await();
System.out.println("Finish countDownLatch Test");
}
}
运行结果:
情况②:设定核心线程数与遍历次数和countdownLatch不等时,也是同样的效果。
注:执行完的线程也会进入阻塞状态
public class CountDownLatchTest {
private static final int size = 8;
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = new ThreadPoolExecutor(5,10, 0,TimeUnit.SECONDS,
new LinkedBlockingDeque<Runnable>());
CountDownLatch countDownLatch = new CountDownLatch(size);
IntStream.range(0,size).forEach(
r-> executorService.execute( () -> {
System.out.println(Thread.currentThread().getName() + " start countDownLatch Test" + r);
try {
Thread.sleep(1000); //模拟耗时操作
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " end countDownLatch Test"+ r);
countDownLatch.countDown();
})
);
executorService.shutdown();
countDownLatch.await();
System.out.println("Finish countDownLatch Test");
}
做法是初始化一个共享的 CountDownLatch 对象,将其计数器初始化为 1 :new CountDownLatch(1),多个线程在开始执行任务前首先 coundownlatch.await(),当主线程调用 countDown() 时,计数器变为 0,多个线程同时被唤醒。
public class CountDownLatchTest1 {
private static final int size = 8;
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = new ThreadPoolExecutor(5,10, 0,TimeUnit.SECONDS,
new LinkedBlockingDeque<Runnable>());
CountDownLatch countDownLatch = new CountDownLatch(1);
IntStream.range(0,size).forEach(
r-> executorService.execute( () -> {
System.out.println(Thread.currentThread().getName() + " start countDownLatch Test" + r);
try {
countDownLatch.await();
Thread.sleep(1000);//模拟耗时操作
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " end countDownLatch Test"+ r);
})
);
executorService.shutdown();
countDownLatch.countDown();
System.out.println("Finish countDownLatch Test");
}
}
一个非常方便的使用场景是,你可以使用 n 个线程访问共享资源,在每次测试阶段的线程数目是不同的,并尝试产生死锁。
public class CountDownLatchTest2 {
public static void main(String[] args) throws InterruptedException {
System.out.println("Hello World!");
ExecutorService executorService = Executors.newFixedThreadPool(2);
byte[] i = new byte[0];
byte[] j = new byte[0];
final CountDownLatch countDownLatch = new CountDownLatch(2);
executorService.execute(new DeadThread1(i, j,countDownLatch));
executorService.execute(new DeadThread2(i, j,countDownLatch));
countDownLatch.await();
System.out.println("done !!!");
}
public static class DeadThread1 implements Runnable {
private byte[] i;
private byte[] j;
private CountDownLatch countDownLatch;
public DeadThread1(byte[] i, byte[] j, CountDownLatch countDownLatch) {
this.i = i;
this.j = j;
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
synchronized (i) {
try {
System.out.println(Thread.currentThread().getName() + "step1 is running!!");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (j) {
System.out.println(Thread.currentThread().getName() + " step2 is running!!");
countDownLatch.countDown();
System.out.println(Thread.currentThread().getName() + " step3 is end!!");
}
}
}
}
public static class DeadThread2 implements Runnable {
private byte[] i;
private byte[] j;
private CountDownLatch countDownLatch;
public DeadThread2(byte[] i, byte[] j, CountDownLatch countDownLatch) {
this.i = i;
this.j = j;
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
synchronized (j) {
try {
System.out.println(Thread.currentThread().getName() + " step1 is running!!");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (i) {
System.out.println(Thread.currentThread().getName() + " step2 is running!!");
countDownLatch.countDown();
System.out.println(Thread.currentThread().getName() + " step3 is end!!");
}
}
}
}
}
分析:由于发生死锁,所以子线程并没有执行countdown()方法,所以主线程调用await()发生阻塞,没有打印出“done !!!”
运行结果:
源码:
CountDownLatch类内,与ReentrantLock类似,有静态内部类AbstractQueuedSynchronizer的Sync
,并重写了父类的方法
public class CountDownLatch {
/**
* Synchronization control For CountDownLatch.
* Uses AQS state to represent count.
*/
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;
}
}
}
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
/**
* 同步器释放一个资源,计算器减1
**/
public void countDown() {
sync.releaseShared(1);
}
public final boolean releaseShared(int arg) {
//判断是否能释放资源
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
protected boolean tryReleaseShared(int releases) {
// Decrement count; signal when transition to zero
//自旋
for (;;) {
//获得当前计数器的数值
int c = getState();
if (c == 0)
//如果计数器为0,直接返回
return false;
int nextc = c-1;
//调用cas,设置修改state = c-1
if (compareAndSetState(c, nextc))
return nextc == 0;
}
}
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
//如果当前计数器state为0,await()执行完成
//如果当前计数器state部位0,调用doAcquireSharedInterruptibly,当前线程进入阻塞状态
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1;
}
CountDownLatch 是一次性的,计数器的值只能在构造方法中初始化一次,之后没有任何机制再次对其设置值,当 CountDownLatch 使用完毕后,它不能再次被使用。