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;
}
}
}
同步倒数计数器CountDownlatch
最新推荐文章于 2022-03-28 13:52:27 发布