方法及解释 public CountDownLatch(int count)参数传递线程数,表示等待线程数量 public void await()让线程等待 public void countDown()当前线程执行完毕 使用场景 让某一条线程等待其他线程执行完毕之后再执行
利用案例加深印象: 利用CountDownLatch创建对象管理3个线程 通过第4个线程完成收尾动作
代码实现:(一个妈妈收尾和三个小孩吃饺子的案例) //测试类:
public class countdownLatchdemo {
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(3);
mothercountdown mo = new mothercountdown(countDownLatch);
mo.start();
child1 c1 = new child1(countDownLatch);
c1.setName("小明");
child2 c2 = new child2(countDownLatch);
c2.setName("小刚");
child3 c3 = new child3(countDownLatch);
c3.setName("小红");
c1.start();
c2.start();
c3.start();
}
}
//妈妈类:
public class mothercountdown extends Thread{
private CountDownLatch countDownLatch;
public mothercountdown(CountDownLatch countDownLatch) {
this.countDownLatch=countDownLatch;
}
@Override
public void run() {
//等待孩子吃完
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
//收拾碗筷
System.out.println("妈妈去收拾碗筷");
}
}
//分别是3个小娃娃类:
public class child1 extends Thread{
private CountDownLatch countDownLatch;
public child1(CountDownLatch countDownLatch) {
this.countDownLatch=countDownLatch;
}
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
//吃饺子
System.out.println(getName()+"正在吃第"+i+"饺子");
}
//吃完说一声
countDownLatch.countDown();
}
}
public class child2 extends Thread{
private CountDownLatch countDownLatch;
public child2(CountDownLatch countDownLatch) {
this.countDownLatch=countDownLatch;
}
@Override
public void run() {
for (int i = 1; i <= 15; i++) {
//吃饺子
System.out.println(getName()+"正在吃第"+i+"饺子");
}
//吃完说一声
countDownLatch.countDown();
}
}
public class child3 extends Thread{
private CountDownLatch countDownLatch;
public child3(CountDownLatch countDownLatch) {
this.countDownLatch=countDownLatch;
}
@Override
public void run() {
for (int i = 1; i <= 20; i++) {
//吃饺子
System.out.println(getName()+"正在吃第"+i+"饺子");
}
//吃完说一声
countDownLatch.countDown();
}
}
个人小结:
1. CountDownLatch(int count):参数写等待线程的数量。并定义了一个计数器。
2. await():让线程等待,当计数器为0时,会唤醒等待的线程
3. countDown(): 线程执行完毕时调用,会将计数器-1。