Java并发-25.并发工具类-CountDownLatch

2019-06-05 17:28:42 浏览数 (1)

等待多线程完成的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() {
代码语言:javascript复制
@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()方法阻塞当前线程,直到计数器变成零。
代码语言:javascript复制
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);
    }
}

0 人点赞