1.countDownLatch
阻塞,countDown到零,结束阻塞继续执行。可以时一个线程countDown,可以是多个线程countDown
public static void usingCountDownLatch(){ Thread[] threads = new Thread[100]; CountDownLatch latch = new CountDownLatch(threads.length); for (int i = 0; i < threads.length; i++){ threads[i] = new Thread(() -> { int result = 0; for (int j = 0; j<10000; j++) result += j; latch.countDown(); }); } for (int i = 0; i< threads.length; i++){ threads[i].start(); } try{ latch.await(); //阻塞,当countDown为0时,阻塞放开。 所有运行线程结束了,才结束阻塞 }catch (InterruptedException e){ e.printStackTrace(); } }
2.CyclicBarrier
阻塞n个线程,数量达到了继续执行
public static void main(String[] args) { //参数:parties:满多少人,new Runnable 要执行的任务 CyclicBarrier barrier = new CyclicBarrier(20, new Runnable() { @Override public void run() { System.out.println("满人,发车。 let's go"); } }); //不同的写法 CyclicBarrier b = new CyclicBarrier(20); CyclicBarrier b1 = new CyclicBarrier(20, ()->{ System.out.println("let's go"); }); for (int i = 0; i< 100; i++){ new Thread(() -> { try{ barrier.await(); }catch (InterruptedException e){ e.printStackTrace(); }catch (BrokenBarrierException e){ e.printStackTrace(); } }).start(); } }