package cm.concurrent;import java.util.concurrent.CountDownLatch;public class UseContDownLatch { public static void main(String[] args) { //2表示唤醒的次数,如果没有达到唤醒的次数,countDownLatch.await();之后的业务将无法执行! final CountDownLatch countDownLatch = new CountDownLatch(2); Thread t1=new Thread(new Runnable() { @Override public void run() { try { System.out.println("进入t1线程,等待其他线程处理完成........."); countDownLatch.await(); System.out.println("t2和t3初始化完成,t1才能线程继续执行................."); } catch (Exception e) { e.printStackTrace(); } } },"t1"); Thread t2=new Thread(new Runnable() { @Override public void run() { try { System.out.println("进入t2线程进行初始化........."); Thread.sleep(3000); System.out.println("t2说:t1线程可以继续执行................."); //第一次唤醒 countDownLatch.countDown(); } catch (Exception e) { e.printStackTrace(); } } },"t2"); Thread t3=new Thread(new Runnable() { @Override public void run() { try { System.out.println("进入t3线程进行初始化........."); Thread.sleep(4000); System.out.println("t3说:t1线程可以继续执行................."); //第二次唤醒 countDownLatch.countDown(); } catch (Exception e) { e.printStackTrace(); } } },"t3"); t1.start(); t2.start(); t3.start(); }}
确切的来说,第一次唤醒和第二次唤醒并不是绝对的,因为线程中每个线程争取cpu的先后顺序都书随机的,哪个先执行,哪个就是第一次唤醒。