栅栏(java并发编程实战5.5.4)

栅栏类似于闭锁,它能阻塞一组线程直到某个事件发生。栅栏与闭锁的关键区别在于,所有线程必须同时到达栅栏位置,

才能继续执行。闭锁用于等待事件,而栅栏用于等待其他线程,且能够重复执行。

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

public class TestCyclicBarrier {
	
	private final CyclicBarrier barrier;
	private final Worker[] workers;
	
	public TestCyclicBarrier() {
		int count = Runtime.getRuntime().availableProcessors();
		barrier = new CyclicBarrier(count, new Runnable() {
			@Override
			public void run() {
				System.out.println("所有线程均到达栅栏位置,开始下一轮");
			}
		});
		this.workers = new Worker[count];
		for(int i = 0; i < count; i++) {
			workers[i] = new Worker(i);
		}
	}

	private class Worker implements Runnable {
		int i;
		
		public Worker(int i) {
			this.i = i;
		}

		@Override
		public void run() {
			for(int index = 1; index < 3; index++) {
				System.out.println("线程" + i + "第" + index + "次到达栅栏位置,等待其他线程!");
				try {
					barrier.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (BrokenBarrierException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	
	public void start() {
		for(int i = 0; i < workers.length; i++) {
			new Thread(workers[i]).start();
		}
	}
	
	public static void main(String[] args) {
		new TestCyclicBarrier().start();
	}
	
}


你可能感兴趣的:(java多线程,栅栏,并发,线程)