屏障攔截,構造參數能夠傳遞攔截的線程數量,以及攔截後調用的Runnable類。每當線程調用await方法的時候,就告訴CyclicBarrier已經到達了屏障,而後阻塞在那邊,等所有線程都到達了屏障,線程開始執行。ide
public class CyclicBarrierDemo { static CyclicBarrier cyclicBarrier = new CyclicBarrier(2, new Thread3()); static int num = 0; static class Thread1 implements Runnable { @Override public void run() { try { num += 1; Thread.sleep(5000); cyclicBarrier.await(); System.out.println(Thread.currentThread().getName() + "-" + 1); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } } static class Thread2 implements Runnable { @Override public void run() { try { num += 1; Thread.sleep(1000); cyclicBarrier.await(); System.out.println(Thread.currentThread().getName() + "-" + 2); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } } static class Thread3 implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName() + ":num=" + num); } } public static void main(String[] args) { Thread thread1 = new Thread(new Thread1(), "thread1"); Thread thread2 = new Thread(new Thread2(), "thread2"); thread1.start(); thread2.start(); System.out.println(Thread.currentThread().getName() + ":" + 0); } }
運行結果以下:
線程3等到線程1和線程2同時到達屏障後,才執行,這個時候,取到的num就是2了。
線程2休眠了1秒,線程1休眠了5秒,可是線程2並無先執行,因此他是在等線程1到達屏障。spa
好比上課點名,有些老師很隨意,只要人數滿了,就開始上課,無論有部分學生變音喊到,都記有人來上課,這個時候就是CountDownLatch。有些課程沒有老師,位置坐滿人了,AI播放視頻開始上課,這個時候就是CyclicBarrier。線程