java thread barrier CyclicBarrier

CyclicBarrier allows a group of threads to wait for each other when they reach a common barrier point. It is very useful in programs involving fixed-size thread groups, and these threads must wait for each other, CyclicBarrier can be reused after the waiting thread is released.
insert image description here

Construction method

CyclicBarrier(int parties)
creates a new barrier and sets the number of parties that will visit this barrier.
CyclicBarrier(int parties, Runnable barrierAction)
creates a new barrier and sets the number of barriers that will be visited, and executes the code in the Runnable thread after all threads have reached the barrier point.

method

int await()
waits for all threads calling this method to reach this barrier.

int await(long timeout, TimeUnit unit)
waits for all threads calling this method to reach this barrier, if the set time is exceeded, an exception is thrown, and if it is less than or equal to 0, it does not wait (throws an exception)

int getNumberWaiting()
returns the number of barrier points currently reached.

int getParties()
returns the number of barrier points that are set in the constructor.


Whether the barrier point set by boolean isBroken() is broken, if the time set by await times out or is 0, and an exception is thrown, the barrier point has been broken, return true, and return false normally

void reset()
resets the barrier point to its initial state. If there are waiting threads, an error will be reported. If the barrier is broken, it is better to reset a new barrier instead of initialization.

Use DEMO

public class TestDemo {
    
    
	
	private static int index = 0;
	
    public static void main(String[] args) throws InterruptedException {
    
    
    	
    	CyclicBarrier barrier = new CyclicBarrier(3, ()->{
    
    
    		System.out.println("全部线程都达到了设置的拦截点");
    		
    	});
    	for (int i = 0; i < 3; i++) {
    
    
    		Thread.sleep(1000);
    		index = i;
			new Thread(()->{
    
    
				System.out.println("启动了一个线程【"+index+"】,到达了拦截点");
				try {
    
    
					barrier.await();
				} catch (InterruptedException | BrokenBarrierException e) {
    
    
					e.printStackTrace();
				}
				System.out.println("每个线程都能继续执行了");
			}).start();
		}
    	    	
    }

}

result

启动了一个线程【0】,到达了拦截点
启动了一个线程【1】,到达了拦截点
启动了一个线程【2】,到达了拦截点
全部线程都达到了设置的拦截点
每个线程都能继续执行了
每个线程都能继续执行了
每个线程都能继续执行了

Guess you like

Origin blog.csdn.net/ren365880/article/details/130159442