闭锁的概念: (线程)等待一个或一些线程执行完后,在开始执行。(具体自行看下概念)
模拟火箭发射
package com.fjf.juc;
import java.util.concurrent.CountDownLatch;
/**
* 闭锁 火箭发射
* @author fjf
* 2018年9月11日 14:50:28
*/
public class TestCountdownlatch {
public static void main(String[] args) {
//发射火箭需要的工作准备 n项
int preparework = 6;
final CountDownLatch c = new CountDownLatch(preparework);
/**
* 不同的线程,不同的工作小组,做不同的工作
*/
for ( int i = preparework; i > 0; i--) {
/* try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}*/
new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println( Thread.currentThread().getName()+"准备好了");
} catch (Exception e) {
e.printStackTrace();
}finally{
c.countDown();
}
}
}).start();
}
try {
//准备工作 都做完后,才开始发射
c.await();
System.out.println("发射...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}