总结:当我们多个处理之间存在先后关系的时候,可以通过countDownLatch来控制
countDownLatch 类用于多线程间
//调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行
public void await() throws InterruptedException { };
//和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行
public boolean await(long timeout, TimeUnit unit) throws InterruptedException { };
//将count值减1
public void countDown() { };
一般countDown()和await() 组合使用,控制一块整理的逻辑处理。
@Testpublic void countDownTest(){ExecutorService thread1 = Executors.newSingleThreadExecutor();ExecutorService thread2 = Executors.newSingleThreadExecutor();// 初始化长度给定是2CountDownLatch latch = new CountDownLatch(2);// 线程1thread1.execute(() -> {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("第一个线程" + Thread.currentThread().getName());// 执行过后此线程,latch.countDown();});// 线程1thread2.execute(() -> {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("第二个线程" + Thread.currentThread().getName());// 执行过后此线程,latch.countDown();});System.out.println("进入等待");try {// 这边需要等latch值为0的时候才会继续执行后面代码latch.await();} catch (InterruptedException e) {e.printStackTrace();}System.out.println("等待两个个线程执行完毕…… ……");}
执行结果:
多线程的情况,会等到所有的线程都countdown=0,才会执行await()后面的操作
@Testpublic void countDownTest() {// 创建一个线程池,可动态加线程数ExecutorService pool = Executors.newCachedThreadPool();CountDownLatch cdl = new CountDownLatch(5);for (int i = 0; i < 5; i++) {pool.execute(() -> {try {synchronized (cdl) {/*** 每次减少一个容量*/System.out.println("thread counts = " + Thread.currentThread().getName() + (cdl.getCount()));cdl.countDown();}cdl.await();System.out.println("concurrency counts = " + (5 - cdl.getCount()));} catch (Exception e) {e.printStackTrace();}});}try {// 等待一下,防止上面线程没执行结束,就退出了Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}
执行结果: