美文网首页
Java并发编程(一):CountDownLatch

Java并发编程(一):CountDownLatch

作者: 尹学姐 | 来源:发表于2018-06-12 21:04 被阅读0次

    Java并发编程:CountDownLatch

    简介

    CountDownLatch是在Java1.5中引入的同步工具类,它允许一个或多个线程一直等待,直到其他线程执行完后再执行。

    实现原理

    CountDownLatch是通过一个计数器来实现的,计数器的初始值为线程的数量。每当一个线程完成了自己的任务后,计数器的值就会减1。当计数器值到达0时,它表示所有的线程已经完成了任务,然后在闭锁上等待的线程就可以恢复执行任务。

    image

    主要方法

    // 构造方法,count数不可更改
    public CountDownLatch(int count) {  };
    
    //调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行
    public void await() throws InterruptedException { };
    //和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行
    public boolean await(long timeout, TimeUnit unit) throws InterruptedException { };  
    // 将count值减一
    public void countDown() { };
    

    示例

    • 简单示例
    public class Test {
         public static void main(String[] args) {   
             final CountDownLatch latch = new CountDownLatch(2);
              
             new Thread(){
                 public void run() {
                     try {
                         System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");
                        Thread.sleep(3000);
                        System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");
                        latch.countDown();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                 };
             }.start();
              
             new Thread(){
                 public void run() {
                     try {
                         System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");
                         Thread.sleep(3000);
                         System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");
                         latch.countDown();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                 };
             }.start();
              
             try {
                 System.out.println("等待2个子线程执行完毕...");
                latch.await();
                System.out.println("2个子线程已经执行完毕");
                System.out.println("继续执行主线程");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
         }
    }
    
    • 在应用程序启动前,先判断外部服务已经启动
      ImportNew文章

    相关文章

      网友评论

          本文标题:Java并发编程(一):CountDownLatch

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