多執行緒下的其它元件之CyclicBarrier、Callable、Future、FutureTask
阿新 • • 發佈:2018-12-30
public static class CyclicBarrierThread extends Thread { private CyclicBarrier cb; private int sleepSecond; public CyclicBarrierThread(CyclicBarrier cb, int sleepSecond) { this.cb = cb; this.sleepSecond = sleepSecond; } public void run() {try { System.out.println(this.getName() + "運行了"); Thread.sleep(sleepSecond * 1000); System.out.println(this.getName() + "準備等待了, 時間為" + System.currentTimeMillis()); cb.await(); System.out.println(this.getName() + "結束等待了, 時間為" + System.currentTimeMillis()); }catch (Exception e) { e.printStackTrace(); } } } public static void main(String[] args) { Runnable runnable = new Runnable() { public void run() { System.out.println("CyclicBarrier的所有執行緒await()結束了,我運行了, 時間為" + System.currentTimeMillis()); } }; CyclicBarrier cb= new CyclicBarrier(3, runnable); CyclicBarrierThread cbt0 = new CyclicBarrierThread(cb, 3); CyclicBarrierThread cbt1 = new CyclicBarrierThread(cb, 6); CyclicBarrierThread cbt2 = new CyclicBarrierThread(cb, 9); cbt0.start(); cbt1.start(); cbt2.start(); }