闭锁(Latch)
闭锁(Latch):一种同步工具类,可以延迟线程的进度直到其到达终止状态。其作用相当于一扇门,这扇门打开之前,所有线程的将被阻塞在门前,只有在门打开后,所有的线程才能通过。并且门(闭锁)的状态是一次性的(栅栏则是可控),只要门一打开,就不能再关闭。闭锁可以用来确保某些活动直到其它活动都完成后才继续执行。
CountDownLatch是java.util.concurrent包里关于闭锁的一种实现,其API如下:
public CountDownLatch(int count)
// 使当前线程在锁存器倒计数至零之前一直等待,除非线程被中断
public void await() throws InterruptedException
// 使当前线程在锁存器倒计数至零之前一直等待,除非线程被 中断或超出了指定的等待时间。
public boolean await(long timeout, TimeUnit unit) throws InterruptedException
// 倒计数
public void countDown()
// 返回当前计数
public long getCount()
上代码(JCIP5-5加上注释和main()):
/**
* TestHarness Using CountDownLatch for starting and stopping threads in timing
* tests
*
* @author Brian Goetz and Tim Peierls
* @author Modified by alchimie
*/
public class TestHarness {
public long timeTasks(int nThreads, final Runnable task)
throws InterruptedException {
// 起始门
final CountDownLatch startGate = new CountDownLatch(1);
// 终止门
final CountDownLatch endGate = new CountDownLatch(nThreads);
for (int i = 0; i < nThreads; i++) {
Thread t = new Thread() {
public void run() {
try {
System.out.println("线程"
+ Thread.currentThread().getName() + "等待执行");
// 线程等待闭锁打开
startGate.await();
try {
task.run();
} finally {
endGate.countDown();
}
} catch (InterruptedException ignored) {
}
}
};
t.start();
}
long start = System.nanoTime();
// 加入一小段等待时间让所有线程就绪
Thread.sleep(100);
startGate.countDown();
System.out.println("线程" + Thread.currentThread().getName() + "等待");
// 主线程等待所有子线程运行结束
endGate.await();
System.out.println("线程" + Thread.currentThread().getName() + "执行");
long end = System.nanoTime();
return end - start;
}
public static void main(String args[]) {
TestHarness th = new TestHarness();
try {
long time = th.timeTasks(5, new Thread(new Runnable() {
public void run() {
System.out.println("线程" + Thread.currentThread().getName()
+ "执行完毕");
}
}));
System.out.println("统计时间" + time);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
执行结果:
线程Thread-1等待执行
线程Thread-4等待执行
线程Thread-3等待执行
线程Thread-2等待执行
线程Thread-5等待执行
线程main等待
线程Thread-1执行完毕
线程Thread-5执行完毕
线程Thread-2执行完毕
线程Thread-3执行完毕
线程Thread-4执行完毕
线程main执行
统计时间100455504
本文介绍Java并发工具类CountDownLatch的基本概念及其应用场景,并提供了一个详细的示例代码,展示如何利用CountDownLatch来协调多线程间的启动与停止。

被折叠的 条评论
为什么被折叠?



