java CyclicBarrier usage

CyclicBarrier is mainly used to wait for a group of threads to execute to a certain time.
The difference between it and CountDownLatch: CountDownLatch is used to wait for an event, while CountDownLatch is used to wait for a thread.
Below is an example:
public class CycleBarrierTest implements Runnable {
	private CyclicBarrier cyclicBarrier;

	public CycleBarrierTest(CyclicBarrier cyclicBarrier) {
		this.cyclicBarrier = cyclicBarrier;
	}

	@Override
	public void run() {
		System.out.println("Ready to execute the task");
		try {
			Thread.sleep(5000);
			System.out.println("Complete task execution");
			cyclicBarrier.await();
		} catch (Exception e) {
			e.printStackTrace ();
		}
		System.out.println("Execute other tasks");
	}
	
	public static void main(String[] args) {
		CyclicBarrier barrier = new CyclicBarrier(3);
		for(int i=0;i<3;i++){
			CycleBarrierTest barrierTest = new CycleBarrierTest(barrier);
			Thread thread = new Thread(barrierTest);
			thread.start();
		}
	}

}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326614808&siteId=291194637