1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| public class CyclicBarrierDemo {
static class Tourist extends Thread { CyclicBarrier barrier; public Tourist(CyclicBarrier barrier) { this.barrier = barrier; } @Override public void run() { try { Thread.sleep((int) (Math.random() * 1000)); barrier.await(); System.out.println(this.getName() + " arrived A " + System.currentTimeMillis()); Thread.sleep((int) (Math.random() * 1000)); barrier.await(); System.out.println(this.getName() + " arrived B " + System.currentTimeMillis()); } catch(InterruptedException e) { } catch(BrokenBarrierException e) { } } } public static void main(String[] args) { int num = 3; Tourist[] threads = new Tourist[num]; CyclicBarrier barrier = new CyclicBarrier(num, new Runnable() { @Override public void run() { System.out.println("all arrived " + System.currentTimeMillis() + " executed by " + Thread.currentThread().getName()); } }); for(int i=0; i<num; i++) { threads[i] = new Tourist(barrier); threads[i].start(); } } }
|