适用场景:
任务3需等待任务1和任务2完成后才可以执行
示例如下:
public static void main(String[] args) { //需要明确等待的线程总数 CountDownLatch c1 = new CountDownLatch(10); MyCache myCache = new MyCache(); for (int i = 1; i <= 5; i++) { final int temp = i; new Thread(new Runnable() { @Override public void run() { myCache.put(temp + "", temp + ""); //在线程run方法内部,最后一步执行countDown,计数器-1操作 c1.countDown(); } }, "thread-" + i).start(); } for (int i = 1; i <= 5; i++) { final int temp = i; new Thread(new Runnable() { @Override public void run() { myCache.get(temp + ""); } }, "thread-" + i).start(); } for (int i = 6; i <= 10; i++) { final int temp = i; new Thread(new Runnable() { @Override public void run() { myCache.put(temp + "", temp + ""); c1.countDown(); } }, "thread-" + i).start(); } try { c1.await(); System.out.println(myCache.getMap()); } catch (InterruptedException e) { e.printStackTrace(); } }主线程调用await等待之前任务结束
当然也可以用Future实现上述功能