java并发:CyclicBarrier的使用

package com;

import java.awt.MultipleGradientPaint.CycleMethod;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * CyclicBarrier 用设置多少个线程执行完成之后才接下来执行
 *
 * 门禁系统实例
 */

public class CyclicBarrierDemo {
	public final int STUDENT_COUNT = 12;
	
	public CyclicBarrier mBarrider = new CyclicBarrier(3, new Runnable() {
		
		@Override
		public void run() {
			//当执行的线程满足三个时候,就现在执行该方法体
			System.out.println("校门打开...");
		}
	});
	
	public void goHome() throws InterruptedException, BrokenBarrierException{
		System.out.println(Thread.currentThread().getName() + " " + "刷卡,等等回家...");
		mBarrider.await();//验证是否能够放行
		//System.out.println(Thread.currentThread().getName() + " " + "回家了***");
	}
	
	public static void main(String[] args) {
		final CyclicBarrierDemo demo = new CyclicBarrierDemo();
		
		for(int i = 0 ; i < demo.STUDENT_COUNT ; i ++){
			new Thread("学生" + i + " ") {
				
				@Override
				public void run() {
					try {
						demo.goHome();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}.start();
		}
	}
}

你可能感兴趣的:(java并发:CyclicBarrier的使用)