CountDownLacth
CountDownLacth(倒计数锁存器)到底有什么用呢?我们来看下面这个场景。
我们又有小片片要开始拍摄了,这个小片片需要5个演员来演,开演之前,导演需要这5个演员全部准备好才能Action,5个演员听到导演叫Action就开演了。
使用CountDownLacth完成以上场景。
public class CountDownLatchDemo {
private static final Random RANDOM = new Random();
private static final String[] ACTORS ={
"波多野结衣","吉泽明步","苍井空","小泽玛利亚","泷泽萝拉"};
static class Actor implements Runnable{
private String name ;
private CountDownLatch readyLacth;
private CountDownLatch startLacth;
public Actor(String name,CountDownLatch readyLacth,CountDownLatch startLacth){
this.name = name;
this.readyLacth = readyLacth;
this.startLacth = startLacth;
}
@Override
public void run() {
try {
int readyTime = RANDOM.nextInt(1000);
System.out.println(name + ":我需要" + readyTime/100 + "分钟时间准备.");
//模拟准备时间
Thread.sleep(readyTime);
System.out.println(name + ":我已经准备好了!");
readyLacth.countDown();
//等待导演发令
startLacth.await();
System.out.println(name + ":我开始表演了,aaaaa,oooooooo,kimoji");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
//导演的Lacth,每个演员准备好,该Latch就-1,需要等待所有演员准备好
CountDownLatch readyLacth = new CountDownLatch(ACTORS.length);
//演员的Lacth,需要等待导演叫开始,该latch -1
CountDownLatch startLacth = new CountDownLatch(1);
ExecutorService executorService = Executors.newCachedThreadPool();
for(int i=
今天的文章CountDownLatch & CyclicBarrier & Semaphore分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/65953.html