闭锁:确保多个线程在完成各自事务后,才会打开继续执行后面的内容,否则一直等待。
- 例子1:执行线程打印一下执行的时间
public static void main(String[] args) {
long start = System.currentTimeMillis();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i <= 10; i++) {
System.out.println(i);
}
}
}).start();
long end = System.currentTimeMillis();
System.out.println("===>"+ (end-start));
}
}
结果:执行时间在前面就打印了
===>4
0
1
2
3
4
5
6
7
8
9
10
怎么让打印执行时间在后面才执行呢,那就要到闭锁了(CountDownLatch),优化一下
public class ThreadDemo2 implements Runnable {
private final CountDownLatch latch;
public ThreadDemo2(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
for (int i = 0; i < 5000; i++) {
System.out.println(i);
}
latch.countDown();//当前事件执行完毕,计数 -1
}
public static void main(String[] args) {
// 申明,等待事件数量 5次
CountDownLatch latch = new CountDownLatch(5);
// 依次创建并启动处于等待状态的5个线程
ThreadDemo2 threadDemo2 = new ThreadDemo2(latch);
long start = System.currentTimeMillis();
for (int i = 0; i < 5; i++) {
new Thread(threadDemo2).start();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("===>"+ (end-start));
}
}
结果:CountDownLatch 内部维护一个计数器(new CountDownLatch(5)),当 latch.countDown() 的时候计数会减1,latch.await() 的时候等待计数器 = 0,所有await的线程都会阻塞,直到计数器为0或者等待线程中断或者超时。
...
6
7
8
9
10
===>4