◆
CountDownLatch
◆
假如有一个任务想要往下执行,但必须要等到其他的任务执行完毕后才可以。
比如你想要买套房子,但是呢你现在手上没有钱。你得等这个月工资发了、然后年终奖发了、然后朋友借你得钱还给你了、然后再给朋友借一部分才可以买,这种场景你就可以使用CountDownLatch。
CountDownLatch是JDK为我们提供的一个计数器,它的操作是原子操作,同一时间只能有一个线程去操作这个它。
我们先来看一下CountDownLatch的主要方法。
1 2 3 4 5 6 7 8 9 10 |
//构造方法,接收计数器的数量 public CountDownLatch(int count) //持续等待计数器归零 public void await() //最多等待unit时间单位内timeout时间 public boolean await(long timeout, TimeUnit unit) //计数器减1 public void countDown() //返回现在的计数器数量 public long getCount() |
下面是CountDownLatch的基本使用示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public class CountDownLatchDemo { public static CountDownLatch countDownLatch = new CountDownLatch(5); static class ThreadDemo extends Thread { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getId() + "完成任务"); countDownLatch.countDown(); } } public static void main(String[] args) throws InterruptedException { for (int i = 0; i < 5; i++) { new ThreadDemo().start(); } countDownLatch.await(); System.out.println("全部完成 |