java CyclicBarrier for concurrent programming

CyclicBarrier allows a group of threads to wait for each other to reach a common barrier point. CyclicBarrier is useful for scenarios where a group of threads must wait for each other. For example, there is a group of threads that must write operations to the database. Only after all threads write data to the database, these threads can continue to execute. At this time, CyclicBarrier can be used. CyclicBarrier is reusable when all waiting threads are released.

CyclicBarrier has two constructors:

public CyclicBarrier(int parties, Runnable barrierAction)  


public CyclicBarrier(int parties)   


The parameter parties refers to how many threads or tasks are allowed to wait until the barrier state; the parameter barrierAction is the content that will be executed when these threads reach the barrier state.

For CyclicBarrier, the most important is the await() method:



import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierTest {
        // Must wait until all three threads call the c.await() method before the program continues to go down
	static CyclicBarrier c = new CyclicBarrier(3);
	public static void main(String[] args) throws Exception{
		long begin = System.currentTimeMillis();
		AddThread th01 = new AddThread(1, 500000, c);
		AddThread th02 = new AddThread(500001, 1000000, c);
		
		th01.start();
		th02.start();
		// Wait for th01 and th02 to finish executing
		c.await();
		System.out.println(th01.getSum()+th02.getSum());
		System.out.println(System.currentTimeMillis()-begin);
	}
}

class AddThread extends Thread{
	
	private long sum ;
	private long begin ;
	private long end ;
	private CyclicBarrier cb ;
	public AddThread(long begin, long end,CyclicBarrier cb) {
		super();
		this.begin = begin;
		this.end = end;
		this.cb = cb ;
	}
	public long getSum() {
		return sum;
	}
	public long getBegin() {
		return begin;
	}
	public void setBegin(long begin) {
		this.begin = begin;
	}
	public long getEnd() {
		return end;
	}
	public void setEnd(long end) {
		this.end = end;
	}
	@Override
	public void run(){
		try {
			// can be executed first
			for(long i=begin;i<=end;i++){
				sum += i ;
			}
			cb.await();
		} catch (InterruptedException e) {
			e.printStackTrace ();
		} catch (BrokenBarrierException e) {
			e.printStackTrace ();
		}
	}
}








Guess you like

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