美文网首页
Java并发-25.并发工具类-CountDownLatch

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

作者: 悠扬前奏 | 来源:发表于2019-06-03 22:00 被阅读0次

等待多线程完成的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);
    }
}

相关文章

网友评论

      本文标题:Java并发-25.并发工具类-CountDownLatch

      本文链接:https://www.haomeiwen.com/subject/fnivzqtx.html