该文章转自:http://www.itzhai.com/the-introduction-and-use-of-a-countdownlatch.html
CountDownLatch
1、类介绍
一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。用给定的计数 初始化 CountDownLatch。由于调用了 countDown() 方法,所以在当前计数到达零之前,await 方法会一直受阻塞。之后,会释放所有等待的线程,await 的所有后续调用都将立即返回。这种现象只出现一次——计数无法被重置。 一个线程(或者多个), 等待另外N个线程完成某个事情之后才能执行
2、使用场景
在一些应用场合中,需要等待某个条件达到要求后才能做后面的事情;同时当线程都完成后也会触发事件,以便进行后面的操作。 这个时候就可以使用CountDownLatch。CountDownLatch最重要的方法是countDown()和await(),前者主要是倒数一次,后者是等待倒数到0,如果没有到达0,就只有阻塞等待了。
3、方法说明
countDown
public void countDown()
- 递减锁存器的计数,如果计数到达零,则释放所有等待的线程。如果当前计数大于零,则将计数减少。如果新的计数为零,出于线程调度目的,将重新启用所有的等待线程。
如果当前计数等于零,则不发生任何操作。
await
public boolean await(long timeout, TimeUnit unit) throws InterruptedException
- 使当前线程在锁存器倒计数至零之前一直等待,除非线程被中断或超出了指定的等待时间。如果当前计数为零,则此方法立刻返回
true
值。如果当前计数大于零,则出于线程调度目的,将禁用当前线程,且在发生以下三种情况之一前,该线程将一直处于休眠状态:
- 由于调用
countDown()
方法,计数到达零;或者 - 其他某个线程中断当前线程;或者
- 已超出指定的等待时间。
如果计数到达零,则该方法返回
true
值。如果当前线程:
- 在进入此方法时已经设置了该线程的中断状态;或者
- 在等待时被中断,
则抛出
InterruptedException
,并且清除当前线程的已中断状态。如果超出了指定的等待时间,则返回值为false
。如果该时间小于等于零,则此方法根本不会等待。 - 由于调用
- 参数:
timeout
- 要等待的最长时间unit
-timeout
参数的时间单位。- 返回:
- 如果计数到达零,则返回
true
;如果在计数到达零之前超过了等待时间,则返回false
- 抛出:
InterruptedException
- 如果当前线程在等待时被中断
1 public class CountDownLatchTest { 2 3 // 模拟了100米赛跑,10名选手已经准备就绪,只等裁判一声令下。当所有人都到达终点时,比赛结束。 4 public static void main(String[] args) throws InterruptedException { 5 6 // 开始的倒数锁 7 final CountDownLatch begin = new CountDownLatch(1); 8 9 // 结束的倒数锁 10 final CountDownLatch end = new CountDownLatch(10); 11 12 // 十名选手 13 final ExecutorService exec = Executors.newFixedThreadPool(10); 14 15 for (int index = 0; index < 10; index++) { 16 final int NO = index + 1; 17 Runnable run = new Runnable() { 18 public void run() { 19 try { 20 // 如果当前计数为零,则此方法立即返回。 21 // 等待 22 begin.await(); 23 Thread.sleep((long) (Math.random() * 10000)); 24 System.out.println("No." + NO + " arrived"); 25 } catch (InterruptedException e) { 26 } finally { 27 // 每个选手到达终点时,end就减一 28 end.countDown(); 29 } 30 } 31 }; 32 exec.submit(run); 33 } 34 System.out.println("Game Start"); 35 // begin减一,开始游戏 36 begin.countDown(); 37 // 等待end变为0,即所有选手到达终点 38 end.await(); 39 System.out.println("Game Over"); 40 exec.shutdown(); 41 } 42 }
5、输出结果
Game Start
No.9 arrived
No.6 arrived
No.8 arrived
No.7 arrived
No.10 arrived
No.1 arrived
No.5 arrived
No.4 arrived
No.2 arrived
No.3 arrived
Game Over
No.9 arrived
No.6 arrived
No.8 arrived
No.7 arrived
No.10 arrived
No.1 arrived
No.5 arrived
No.4 arrived
No.2 arrived
No.3 arrived
Game Over
资料补充,下面的例子来源于thinking in java(跟上面的例子不同之处在于上面的例子是一个任务等到多个任务执行完成,而thinking in java的就高级一些了,是多个任务等到多个任务执行完成解锁):
代码1:
1 package com.cakushin.thread.countdownlatch; 2 3 import java.util.Random; 4 import java.util.concurrent.CountDownLatch; 5 6 public class TaskPortion implements Runnable { 7 private static int counter = 0; 8 private final int id = counter++; 9 private static Random rand = new Random(47); 10 private final CountDownLatch latch; 11 12 public TaskPortion(CountDownLatch latch){ 13 this.latch = latch; 14 } 15 16 @Override 17 public void run() { 18 try { 19 doWork(); 20 latch.countDown(); 21 } catch (InterruptedException e) { 22 e.printStackTrace(); 23 } 24 } 25 26 private void doWork() throws InterruptedException { 27 Thread.sleep(rand.nextInt(2000)); 28 System.out.println(this + " completed!"); 29 } 30 31 public String toString(){ 32 return String.format("%1$-3d", id); 33 } 34 35 }
代码2:
1 package com.cakushin.thread.countdownlatch; 2 3 import java.util.concurrent.CountDownLatch; 4 5 public class WaitingTask implements Runnable { 6 private static int counter = 0; 7 private final int id = counter++; 8 private final CountDownLatch latch; 9 10 public WaitingTask(CountDownLatch latch){ 11 this.latch = latch; 12 } 13 14 @Override 15 public void run() { 16 try { 17 latch.await(); 18 System.out.println("Latch barrier passed for " + this); 19 } catch (InterruptedException e) { 20 System.out.println(this + " interrupted"); 21 } 22 } 23 24 public String toString(){ 25 return String.format("WatingTask %1$-3d", id); 26 } 27 28 }
代码3:
1 package com.cakushin.thread.countdownlatch; 2 3 import java.util.concurrent.CountDownLatch; 4 import java.util.concurrent.ExecutorService; 5 import java.util.concurrent.Executors; 6 7 public final class CountDownLatchDemo { 8 9 static final int SIZE = 100; 10 11 /** 12 * @author Administrator 13 * @param args 14 */ 15 public static void main(String[] args) { 16 ExecutorService exec = Executors.newCachedThreadPool(); 17 CountDownLatch latch = new CountDownLatch(SIZE); 18 for(int i = 0; i < 10; i++){ 19 exec.execute(new WaitingTask(latch)); 20 } 21 for(int i = 0; i < 100; i++){ 22 exec.execute(new TaskPortion(latch)); 23 } 24 System.out.println("Launched all tasks"); 25 exec.shutdown(); 26 } 27 28 }