多线程之CountDownLatch
CountDownLatch:一个门闩,作用是将某个线程关在门外,等门里的人分赃完毕(计数为0)的时候,才会打开门,让外面的那个线程执行。
这玩意很有用,有利于我们控制许多线程,有序执行业务。
demo:r2必须要等r1执行完才可以执行。
package com.gcc; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public class CountDownLatchTest { public static void main(String[] args) { CountDownLatch c = new CountDownLatch(1); Runnable r1 = ()->{ try { System.out.println("执行r1............"); System.out.println("sleep 1s"); Thread.sleep(1000L); c.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } }; Runnable r2 = ()->{ try { c.await(60L,TimeUnit.SECONDS); System.out.println("执行r2............"); } catch (InterruptedException e) { e.printStackTrace(); } }; new Thread(r2).start(); new Thread(r1).start(); } }
结果:
执行r1............
sleep 1s
执行r2............