CountDownLatch里面有个属性为state,当为零时触发代码往下执行,代码如下:
package threadLock; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class CountDownLatchTest { public static void main(String[] args) { final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(3); ExecutorService service = Executors.newCachedThreadPool(); for (int i = 0; i < 3; i++) { service.execute(new Runnable() { @Override public void run() { try { System.out.println("线程" + Thread.currentThread().getName() + "正在等待命令。"); latch1.await(); System.out.println("线程" + Thread.currentThread().getName() + "正在处理。"); Thread.sleep(new Random().nextInt(1000)); latch2.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } }); } try { Thread.sleep(1000); System.out.println("thread main 发布命令。"); System.out.println("thread main 正在收集各线程响应。"); latch1.countDown(); latch2.await(); System.out.println("thread main已收集所有线程的响应。"); } catch (InterruptedException e) { e.printStackTrace(); } } }