JUC - CountDownLach原理分析

开发 后端
CountDownLatch 和 Semaphore 一样都是共享模式下资源问题,这些源码实现AQS的模版方法,然后使用CAS+循环重试实现自己的功能。

[[345820]]

 CountDownLach闭锁
背景

  • CountDownLatch是在Java1.5被引入,跟它一起被引入的工具类还有CyclicBarrier、Semaphore、ConcurrenthashMap和BlockingQueue。
  • 在java.util.cucurrent包下。

概念

  • CountDownLatch这个类使一个线程等待其它线程各自执行完毕后再执行。
  • 是通过一个计数器来实现的,计数器的初始值是线程的数量。每当一个线程执行完毕后,计数器的值就-1,当计数器的值为0时,表示所有线程都执行完毕,然后在闭锁上等待的线程就可以恢复工作来。

源码

  • countDownLatch类中只提供了一个构造器
  1. public CountDownLatch(int count) { 
  2.   if (count < 0) throw new IllegalArgumentException("count < 0"); 
  3.      this.sync = new Sync(count); 
  • 类中有三个方法是最重要的
  1. // 调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行 
  2. public void await() throws InterruptedException { 
  3.         sync.acquireSharedInterruptibly(1); 
  4.     }//和await()方法类似,只不过等待一定的时间后count值还没变为0的化就会继续执行 
  5. public boolean await(long timeout, TimeUnit unit) 
  6.         throws InterruptedException {        return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); 
  7.     }//将count值减1 
  8. public void countDown() {        sync.releaseShared(1); 
  9.     } 

示例
普通示例:

  1. public class CountDownLatchTest { 
  2.     public static void main(String[] args) { 
  3.         final CountDownLatch latch = new CountDownLatch(2); 
  4.         System.out.println("主线程开始执行…… ……"); 
  5.         //第一个子线程执行 
  6.         ExecutorService es1 = Executors.newSingleThreadExecutor(); 
  7.         es1.execute(new Runnable() { 
  8.             @Override 
  9.             public void run() { 
  10.                 try { 
  11.                     Thread.sleep(3000); 
  12.                     System.out.println("子线程:"+Thread.currentThread().getName()+"执行"); 
  13.                 } catch (InterruptedException e) { 
  14.                     e.printStackTrace(); 
  15.                 } 
  16.                 latch.countDown(); 
  17.             } 
  18.         }); 
  19.         es1.shutdown(); 
  20.         //第二个子线程执行 
  21.         ExecutorService es2 = Executors.newSingleThreadExecutor(); 
  22.         es2.execute(new Runnable() { 
  23.             @Override 
  24.             public void run() { 
  25.                 try { 
  26.                     Thread.sleep(3000); 
  27.                 } catch (InterruptedException e) { 
  28.                     e.printStackTrace(); 
  29.                 } 
  30.                 System.out.println("子线程:"+Thread.currentThread().getName()+"执行"); 
  31.                 latch.countDown(); 
  32.             } 
  33.         }); 
  34.         es2.shutdown(); 
  35.         System.out.println("等待两个线程执行完毕…… ……"); 
  36.         try { 
  37.             latch.await(); 
  38.         } catch (InterruptedException e) { 
  39.             e.printStackTrace(); 
  40.         } 
  41.         System.out.println("两个子线程都执行完毕,继续执行主线程"); 
  42.     } 

结果集:

  1. 主线程开始执行…… …… 
  2. 等待两个线程执行完毕…… ……子线程:pool-1-thread-1执行子线程:pool-2-thread-1执行两个子线程都执行完毕,继续执行主线程 

模拟并发示例:

  1. public class Parallellimit { 
  2.     public static void main(String[] args) { 
  3.         ExecutorService pool = Executors.newCachedThreadPool();        CountDownLatch cdl = new CountDownLatch(100); 
  4.         for (int i = 0; i < 100; i++) { 
  5.             CountRunnable runnable = new CountRunnable(cdl); 
  6.             pool.execute(runnable);        }    }} class CountRunnable implements Runnable { 
  7.     private CountDownLatch countDownLatch; 
  8.     public CountRunnable(CountDownLatch countDownLatch) { 
  9.         this.countDownLatch = countDownLatch; 
  10.     }    @Override 
  11.     public void run() { 
  12.         try { 
  13.             synchronized (countDownLatch) {                /*** 每次减少一个容量*/ 
  14.                 countDownLatch.countDown();                System.out.println("thread counts = " + (countDownLatch.getCount())); 
  15.             }            countDownLatch.await(); 
  16.             System.out.println("concurrency counts = " + (100 - countDownLatch.getCount())); 
  17.         } catch (InterruptedException e) { 
  18.             e.printStackTrace();        }    }} 

源码分析

  1. public class CountDownLatch { 
  2.     //继承AQS来实现他的模板方法(tryAcquireShared,tryReleaseShared) 
  3.     private static final class Sync extends AbstractQueuedSynchronizer {       //计数个数Count 
  4.         Sync(int count) { 
  5.             setState(count);        }        int getCount() { 
  6.             return getState(); 
  7.         }      //AQS方法getState(),返回同步状态,这里指计数器值        protected int tryAcquireShared(int acquires) { 
  8.             return (getState() == 0) ? 1 : -1; 
  9.         }       //循环+cas重试 直到计数器为0 跳出,则release(实现aqs共享模式释放方法) 
  10.         protected boolean tryReleaseShared(int releases) { 
  11.             // Decrement count; signal when transition to zero 
  12.             for (;;) { 
  13.                 int c = getState(); 
  14.                 if (c == 0) 
  15.                     return false
  16.                 int nextc = c-1; 
  17.                 if (compareAndSetState(c, nextc)) 
  18.                     return nextc == 0; 
  19.             }        }    }    private final Sync sync;   //实例化 
  20.     public CountDownLatch(int count) { 
  21.         if (count < 0) throw new IllegalArgumentException("count < 0"); 
  22.         this.sync = new Sync(count);    }    public void await() throws InterruptedException {        sync.acquireSharedInterruptibly(1); 
  23.     }  //带有一个超时时间的awit    public boolean await(long timeout, TimeUnit unit)        throws InterruptedException {        return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); 
  24.     }      public void countDown() {        sync.releaseShared(1); 
  25.     }    public long getCount() {        return sync.getCount(); 
  26.     }} 

总结
CountDownLatch 和 Semaphore 一样都是共享模式下资源问题,这些源码实现AQS的模版方法,然后使用CAS+循环重试实现自己的功能。在RT多个资源调用,或者执行某种操作依赖其他操作完成下可以发挥这个计数器的作用。

责任编辑:姜华 来源: 今日头条
相关推荐

2020-11-03 09:10:18

JUC-Future

2023-04-26 08:39:41

Bitmap元素存储

2021-10-12 17:19:17

Random局限性变量

2022-04-13 08:23:31

Golang并发

2012-12-03 16:57:37

HDFS

2024-01-12 07:38:38

AQS原理JUC

2009-11-06 09:22:46

WCF应用

2021-11-26 17:17:43

Android广播运行原理源码分析

2021-04-21 15:17:10

WebsocketWsnodejs

2021-08-09 11:15:28

MybatisJavaSpring

2015-06-15 10:12:36

Java原理分析

2017-02-09 13:23:46

2023-02-07 09:17:19

Java注解原理

2022-04-12 08:30:45

TomcatWeb 应用Servlet

2015-09-23 16:14:03

Ryu拓扑结构

2012-03-06 11:01:44

Java

2012-12-03 17:12:10

HDFS

2014-08-13 18:47:46

2020-05-27 11:20:37

HadoopSpark大数据

2023-05-31 08:39:04

redis事件驱动
点赞
收藏

51CTO技术栈公众号