并发工具类 CountDownLatch
在多线程中,如果需要一个线程,在其他的线程执行完之后再执行,则需要我们本篇将的并发工具类:CountDownLatch类:
CountDownLatch类的执行原理是:
我们设定的被等待的线程的个数会被记录在底层,当我们的一个线程执行完毕之后调用CountDownLatch类的countDown();方法
那么底层被记录的数字机会减1,当所有的被等待的线程都执行完之后被记录的数字就会变成0,这个时候,等待线程,也就是被CountDownLatch类的await();
方法修饰的线程就会被唤醒。
下面用代码解释一下:(妈妈等待三个孩子吃饺子,三个都吃完再洗刷碗筷)
这是主方法
public static void main(String[] args) { CountDownLatch countDownLatch = new CountDownLatch(3); Child1 child1 = new Child1(countDownLatch); Child2 child2 = new Child2(countDownLatch); Child3 child3 = new Child3(countDownLatch); child1.setName("小明"); child2.setName("小红"); child3.setName("小刚"); mather mom = new mather(countDownLatch); child1.start(); child2.start(); child3.start(); mom.start(); }
这是孩子1
public class Child1 extends Thread { CountDownLatch countDownLatch; public Child1(CountDownLatch countDownLatch) { this.countDownLatch = countDownLatch; } @Override public void run() { for (int i = 0; i < 20; i++) { System.out.println(Thread.currentThread().getName() + "吃了第" + i + "个饺子"); } countDownLatch.countDown(); } }
这是孩子2
public class Child2 extends Thread { CountDownLatch countDownLatch; public Child2(CountDownLatch countDownLatch) { this.countDownLatch = countDownLatch; } @Override public void run() { for (int i = 0; i < 20; i++) { System.out.println(Thread.currentThread().getName() + "吃了第" + i + "个饺子"); } countDownLatch.countDown(); } }
这是孩子3
public class Child3 extends Thread { CountDownLatch countDownLatch; public Child3(CountDownLatch countDownLatch) { this.countDownLatch = countDownLatch; } @Override public void run() { for (int i = 0; i < 20; i++) { System.out.println(Thread.currentThread().getName() + "吃了第" + i + "个饺子"); } countDownLatch.countDown(); } }
这是妈妈:
public class mather extends Thread { CountDownLatch countDownLatch; public mather(CountDownLatch countDownLatch) { this.countDownLatch = countDownLatch; } @Override public void run() { try { countDownLatch.await();//注意要放在执行语句之前 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("开始收拾碗筷"); } }
代码很简单,不做过多解释
迎风少年