1、类介绍
java.util.concurrent
类 CountDownLatch
java.lang.Object
java.util.concurrent.CountDownLatch
2、CountDownLatch作用
一
个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。意思就是说,有一个工厂老板,可以安排
CountDownLatch去监视所有工人工作,等到所有工人都做完了,工厂老板才会可以离开
2、CountDownLatch使用代码
上面代码的意思是说:
/**
* Announce all seeds from configured source to SeedListeners
* (including nonseed lines mixed in).
* @see org.archive.modules.seeds.SeedModule#announceSeeds()
*/
public void announceSeeds() {
if(getBlockAwaitingSeedLines()>-1) { //如果不是需要全部导入种子
final CountDownLatch latch = new CountDownLatch(getBlockAwaitingSeedLines());
new Thread(){
@Override
public void run() {
announceSeeds(latch);
while(latch.getCount()>0) {
latch.countDown();
}
}
}.start();
try {
latch.await();
} catch (InterruptedException e) {
// do nothing
}
} else {
announceSeeds(null);
}
}
上面代码的意思是说:
/**
* Announce all seeds (and nonseed possible-directive lines) from
* the given Reader
* @param reader source of seed/directive lines
* @param latchOrNull if non-null, sent countDown after each line, allowing
* another thread to proceed after a configurable number of lines processed
*/
protected void announceSeedsFromReader(BufferedReader reader, CountDownLatch latchOrNull) {
String s;
/**
* 获取迭代器,什么的迭代器呢?文本文件一行一行读取的迭代器,这个迭代器考虑了注释以#号开始
* 还考虑了空白行,使用正则表达式去处理的,^\\s*[\\S]+\\s*(#.*)?$
* 注释行:\\s*(#.*)?
* */
Iterator<String> iter =
new RegexLineIterator(
new LineReadingIterator(reader),
RegexLineIterator.COMMENT_LINE,
RegexLineIterator.NONWHITESPACE_ENTRY_TRAILING_COMMENT,
RegexLineIterator.ENTRY);
int count = 0;
while (iter.hasNext()) {
s = (String) iter.next();
if(Character.isLetterOrDigit(s.charAt(0))) {
// consider a likely URI
seedLine(s);
count++;
if(count%20000==0) {
System.runFinalization();
}
} else {
// report just in case it's a useful directive
nonseedLine(s);
}
if(latchOrNull!=null) {
latchOrNull.countDown();
}
}
publishConcludedSeedBatch();
}