package com.example.app;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.stream.IntStream;
public class CyclicBarrierTest2 {
private static CyclicBarrier cyclicBarrier=new CyclicBarrier(5, new Runnable() {
@Override
public void run() {
System.out.println("all threads arrived......");
}
});
public static void main(String[] args) {
for(int round=0; round<3;round++){
IntStream.range(0,5).forEach( i -> new Thread(new Runnable() {
@Override
public void run() {
int random= new Random().nextInt(5000);
try {
Thread.sleep(random);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
System.out.println(System.currentTimeMillis()+" "+Thread.currentThread().getName()+" got before barrier......");
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println(System.currentTimeMillis()+" "+Thread.currentThread().getName()+" got after barrier......");
}
}).start());
}
}
}