JavaSE-多线程(6)- CountDownLatch
CountDownLatch是一个同步辅助类,它允许一个或多个线程一直等待直到其他线程执行完毕才开始执行。
join 方法
解释 CountDownLatch 前,先看一个Join 方法的例子:
例1
在下例中,有100个线程同时执行,每个线程在主线程都调用了join方法,最终结果为主线程输出 main start… 后100个线程同时执行,最后主线程输出 main end…
package com.hs.example.base.multithread.day01;
public class JoinTest2 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
public static void main(String[] args) {
final int THREAD_COUNT = 100;
JoinTest2 joinTest2 = new JoinTest2();
System.out.println(Thread.currentThread().getName() + " start...");
Thread[] threads = new Thread[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; i++) {
threads[i] = new Thread(joinTest2, "t" + i);
}
for (int i = 0; i < THREAD_COUNT; i++) {
threads[i].start();
}
for (int i = 0; i < THREAD_COUNT; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " end...");
}
}
执行结果:
main start...
t1 0
t24 0
t1 1
t1 2
t2 0
t2 1
t1 3
t1 4
t24 1
t1 5
t1 6
t1 7
t1 8
t2 2
t0 0
t2 3
t1 9
t9 0
t3 0
t24 2
t3 1
t3 2
t3 3
t9 1
t2 4
t2 5
t0 1
t2 6
......
t47 9
t49 9
main end...
在此例中,join 方法起到线程同步的作用,即主线程会等待其他线程执行完才继续往下执行。
例2
看下如何使用CountDownLatch实现上述功能:
package com.hs.example.base.multithread.day01;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchTest implements Runnable {
private final CountDownLatch countDownLatch ;
public CountDownLatchTest(CountDownLatch countDownLatch){
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
countDownLatch.countDown();
}
public static void main(String[] args) {
final int THREAD_COUNT = 100;
CountDownLatch countDownLatch = new CountDownLatch(THREAD_COUNT);
CountDownLatchTest countDownLatchTest = new CountDownLatchTest(countDownLatch);
System.out.println(Thread.currentThread().getName() + " start...");
Thread[] threads = new Thread[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; i++) {
threads[i] = new Thread(countDownLatchTest, "t" + i);
threads[i].start();
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " end...");
}
}
如上程序中 CountDownLatch 构造方法中 count 值为正在进行的线程数,countDownLatch.await(); 意思是让主线程(main)进入等待队列,从源码中可以看出主线程在加入等待队列后会再次获取当前 state 值并判断是否为0,如果不为 0 则调用 LockSupport.park(this); 方法使主线程进入等待状态,当其他线程完成任务并调用 countDown 方法后,state 值会减一,如果state值减为0,则调用内部 doReleaseShared 方法,从等待队列中取出线程并调用 LockSupport.unpark(s.thread); 方法使得主线程进入就绪状态并继续执行