同步倒数计数器CountDownlatch

package aa;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 同步倒数计数器
 * @author chenjiarong
 *
 */
public class CountdownLatchTest {

	// 等车的学生数
	public static int numberOfperson = 10; 

	// 车开的标志
	public static boolean isGone = false; 

	// 车等待的时间
	public static int carWaitTime = 3; 

	public static void main(String[] args) throws InterruptedException {
		CountDownLatch countDownLatch = new CountDownLatch(numberOfperson);
		new Thread(new GetOn(countDownLatch)).start();
		waitStudentGetOn(countDownLatch);
		driveHome();
	}

	/**
	 * 等待一定时间,不管学生有没有上完车都开走
	 * @param waitStudentsGetOn
	 * @throws InterruptedException
	 */
	private static void waitStudentGetOn(CountDownLatch waitStudentsGetOn)
			throws InterruptedException {
		System.out.println("赶紧的,抓紧时间上车..");
		waitStudentsGetOn.await(carWaitTime, TimeUnit.SECONDS);// 等5秒,还没上车,就开走。。

	}

	/**
	 * 开车
	 * @throws InterruptedException
	 */
	private static void driveHome() throws InterruptedException {
		System.out.println("车走了");
		isGone = true;
	}

	/**
	 * 模拟同学们上车
	 * 
	 * @author chenjiarong
	 * 
	 */
	static class GetOn implements Runnable {

		private CountDownLatch countDownLatch;

		public GetOn(CountDownLatch countDownLatch) {
			super();
			this.countDownLatch = countDownLatch;
		}

		@Override
		public void run() {
			for (int i = 0; i < 10; i++) {
				if (isGone) {
					System.out.println("还有" + (10 - i) + "个学生没上车");
					 break;
				}
				boolean upSuccess = new Student(i + 1).upCar();
				if (upSuccess) {
					countDownLatch.countDown();
				}
			}
		}

	}

	/**
	 * 学生
	 * 
	 * @author chenjiarong
	 * 
	 */
	static class Student {
		// 学生编号
		private int myNum;

		public Student(int num) {
			this.myNum = num;
		}

		/**
		 * 上车动作
		 */
		@SuppressWarnings("static-access")
		public boolean upCar() {
			try {
				// 上车使用的时间,随机
				Thread.currentThread().sleep(new Random().nextInt(2) * 1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (isGone) {
				System.out.println("车开走了");
				return false;
			}
			System.out.println("编号为:" + myNum + "的同学上车了..");
			return true;
		}
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值