以下是一个实际项目中 CountDownLatch 的使用的例子:
private Map afterDecryptFilePathMap = new HashMap();//TODO 注意容器垃圾数据的清理工作
class DecryptRunnable implements Runnable {
private ServerFileBean serverFile;
private Long fid;//指向解密文件
private CountDownLatch decryptSignal;
protected DecryptRunnable(Long fid, ServerFileBean serverFile, CountDownLatch decryptSignal) {
this.fid = fid;
this.serverFile = serverFile;
this.decryptSignal = decryptSignal;
}
@Override
public void run() {
//开始解密
String afterDecryptFilePath = null;
DecryptSignalAndPath decryptSignalAndPath = new DecryptSignalAndPath();
decryptSignalAndPath.setDecryptSignal(decryptSignal);
afterDecryptFilePathMap.put(fid, decryptSignalAndPath);
afterDecryptFilePath = decryptFile(serverFile);
decryptSignalAndPath.setAfterDecryptFilePath(afterDecryptFilePath);
decryptSignal.countDown();//通知所有阻塞的线程
}
}
class DecryptSignalAndPath {
private String afterDecryptFilePath;
private CountDownLatch decryptSignal;
public String getAfterDecryptFilePath() {
return afterDecryptFilePath;
}
public void setAfterDecryptFilePath(String afterDecryptFilePath) {
this.afterDecryptFilePath = afterDecryptFilePath;
}
public CountDownLatch getDecryptSignal() {
return decryptSignal;
}
public void setDecryptSignal(CountDownLatch decryptSignal) {
this.decryptSignal = decryptSignal;
}
}
需要先执行的,被等待线程在这里加入:
CountDownLatch decryptSignal = new CountDownLatch(1);
new Thread(new DecryptRunnable(fid, serverFile, decryptSignal)).start();//无需拿到新线程句柄,由 CountDownLatch 自行跟踪
try {
decryptSignal.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
需要后执行,等待的线程可以这样加入:
CountDownLatch decryptSignal = afterDecryptFilePathMap.get(fid).getDecryptSignal();
try {
decryptSignal.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
如果读者觉得以上示例不够清晰,也可以参考 JDK API 提供的 demo,这个清晰明了:
class Driver2 { // ...
void main() throws InterruptedException {
CountDownLatch doneSignal = new CountDownLatch(N);
Executor e = ...
for (int i = 0; i < N; ++i) // create and start threads
e.execute(new WorkerRunnable(doneSignal, i));
doneSignal.await(); // wait for all to finish
}
}
class WorkerRunnable implements Runnable {
private final CountDownLatch doneSignal;
private final int i;
WorkerRunnable(CountDownLatch doneSignal, int i) {
this.doneSignal = doneSignal;
this.i = i;
}
public void run() {
try {
doWork(i);
doneSignal.countDown();
} catch (InterruptedException ex) {} // return;
}
void doWork() { ... }
}
“Java 多线程编程”系列其他博客: