前言
日常生活中,通常我们完成一件事之后才会接着干下一件事,而一件事可能被分成多个环节由多个人去同步进行,有的人快,有的人慢。但不管怎样,只有全部人都完成了自己负责的环节才算这件事完成了,下一件事才得以继续。这跟java中的CountDownLatch很像,接下来我们就一起探讨下CountDownLatch
一、CountDownLatch概述
示例:一个或者多个线程需要在其它线程都完成任务之后才能执行,其它线程没有完成任务则需要等待。
二、代码示例
1.共享资源CounDown
提供计数方法(其它线程需要完成任务,则需要调用计数方法)、等待方法(其它线程没有完成任务,则需要调用该方法进行等待)
package countdown;
public class CountDown {
private final int total;
private int counter = 0;
public CountDown(int total) {
this.total = total;
}
public synchronized void count() {
counter++;
notifyAll();
}
public synchronized void await() throws InterruptedException {
while (counter != total) {
this.wait();
}
}
}
2.客户端
多个线程进行计数任务,当计数达到某个值之后,才进行下一件事的执行。在计数值没有完成前,执行第二件事的线程需要进行等待
package countdown;
import java.util.Random;
import java.util.stream.IntStream;
public class client {
private final static Random random = new Random(System.currentTimeMillis());
public static void main(String[] args) throws InterruptedException {
System.out.println("任务开始了。。。。。。。。。");
CountDown countDown = new CountDown(5);
IntStream.rangeClosed(1, 5).forEach(x -> new Thread(() -> {
System.out.println("The Thread "+Thread.currentThread().getName() + " is working......");
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
countDown.count();
}, String.valueOf(x)).start());
countDown.await();
System.out.println("第二阶段任务开始。。。。。。。。");
System.out.println("do something");
}
}