由于技术发展,并发,多线程出现,java在java5的时候引进了java.util.concurrent 包。CountDownLatch是在这个并发包下面,是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程的操作执行完后再执行。CountDownLatch 以一个给定的数量初始化。countDown() 每被调用一次,这一数量就减一。通过调用 await() 方法之一,线程可以阻塞等待这一数量到达零。
实例:假设一个下载软件Ant,将文件分为多个块,多个线程同时下载,只有当所有线程都下载完成之后,才可以拼接为一个完整的文件。
传统的做法是使用thread.join
public class AntJoin implements Runnable {
private String id;
private Long cost;
public AntJoin(String id, Long cost) {
this.id = id;
this.cost = cost;
}
@Override
public void run() {
System.out.println(id + " start:");
try {
Thread.sleep(cost);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(id + " end.");
}
public static void main(String[] args) throws Exception {
System.out.println("start download...");
Thread t1 = new Thread(new AntJoin("ANT_11111",5000L));
Thread t2 = new Thread(new AntJoin("ANT_22222",8000L));
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("finish partition download.joint a file.");
}
}
使用CountDownLatch实现
public class Ant implements Runnable {
private String id;
private CountDownLatch latch;
private Long cost;
public Ant(String id, CountDownLatch latch, Long cost) {
this.id = id;
this.latch = latch;
this.cost = cost;
}
@Override
public void run() {
System.out.println(id + " start:");
try {
Thread.sleep(cost);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(id + " end.");
latch.countDown();
}
public static void main(String[] args) {
CountDownLatch latch=new CountDownLatch(2);
System.out.println("start download...");
new Thread(new Ant("ANT_11111",latch,5000L)).start();
new Thread(new Ant("ANT_22222",latch,8000L)).start();
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("finish partition download.joint a file.");
}
}
执行结果:
start download...
ANT_11111 start:
ANT_22222 start:
ANT_11111 end.
ANT_22222 end.
finish partition download.joint a file.
以上内容都是一个大佬发给我学习的实例,我发出来做笔记希望大家一起学习。