static class LatchRunner implements Runnable{
CountDownLatch latch;
public LatchRunner(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
try {
Thread.sleep(200L);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
System.out.println("LatchRunner finish.");
}
}
static class BarrierRunner implements Runnable{
CyclicBarrier barrier;
public BarrierRunner(CyclicBarrier barrier) {
this.barrier = barrier;
}
@Override
public void run() {
try {
Thread.sleep(200L);
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println("BarrierRunner finish.");
}
}
public static void main(String[] args) throws Exception {
CountDownLatch latch = new CountDownLatch(2);
Thread[] threads = {new Thread(new LatchRunner(latch)), new Thread(new LatchRunner(latch))};
threads[0].start();
threads[1].start();
latch.await();
System.out.println("main execute1");
CyclicBarrier barrier = new CyclicBarrier(2);
Thread[] threads2 = {new Thread(new BarrierRunner(barrier)), new Thread(new BarrierRunner(barrier))};
threads2[0].start();
threads2[1].start();
System.out.println("main execute2");
}