等待多线程完成的CountDownLatch
CountDownLatch允许一个或者多个线程等待其他线程完成操作。
- join方法实现,其原理在于不停检查join线程是否完成,如果存活就让当前线程等待,join线程中止后,this.notifyAll()方法调用
/**
两个解析器,需要都解析完之后才能结束
-
@author pengjunzhe
*/
public class JoinCountDownLatchTest {
public static void main(String[] args) throws InterruptedException {
Thread parse1 = new Thread(new Runnable() {@Override public void run() { ; } }); Thread parse2 = new Thread(new Runnable() { @Override public void run() { System.out.println("parser2 finish"); } }); parse1.start(); parse2.start(); parse1.join(); parse2.join(); System.out.println("all parse finished");
}
}
- CountDownLatch实现, countDown()方法计数器减一,await()方法阻塞当前线程,直到计数器变成零。
import java.util.concurrent.CountDownLatch;
/**
* @author pengjunzhe
*/
public class CountDownLatchTest {
static CountDownLatch countDownLatch = new CountDownLatch(2);
public static void main(String[] args) throws InterruptedException {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(1);
countDownLatch.countDown();
System.out.println(2);
countDownLatch.countDown();
}
}).start();
countDownLatch.await();
System.out.println(3);
}
}