CountDownLatch完整源码(基于JDK1.7.0_40)
1 24 25 35 36 package java.util.concurrent; 37 import java.util.concurrent.locks.*; 38 import java.util.concurrent.atomic.*; 39 40 161 public class CountDownLatch { 162 166 private static final class Sync extends AbstractQueuedSynchronizer { 167 private static final long serialVersionUID = 4982264981922014374L; 168 169 Sync(int count) { 170 setState(count); 171 } 172 173 int getCount() { 174 return getState(); 175 } 176 177 protected int tryAcquireShared(int acquires) { 178 return (getState() == 0) ? 1 : -1; 179 } 180 181 protected boolean tryReleaseShared(int releases) { 182 // Decrement count; signal when transition to zero 183 for (;;) { 184 int c = getState(); 185 if (c == 0) 186 return false; 187 int nextc = c-1; 188 if (compareAndSetState(c, nextc)) 189 return nextc == 0; 190 } 191 } 192 } 193 194 private final Sync sync; 195 196 203 public CountDownLatch(int count) { 204 if (count < 0) throw new IllegalArgumentException("count < 0"); 205 this.sync = new Sync(count); 206 } 207 208 235 public void await() throws InterruptedException { 236 sync.acquireSharedInterruptibly(1); 237 } 238 239 280 public boolean await(long timeout, TimeUnit unit) 281 throws InterruptedException { 282 return sync.tryAcquireSharedNanos(1, unit.tonanos(timeout)); 283 } 284 285 295 public void countDown() { 296 sync.releaseShared(1); 297 } 298 299 306 public long getCount() { 307 return sync.getCount(); 308 } 309 310 317 public String toString() { 318 return super.toString() + "[Count = " + sync.getCount() + "]"; 319 } 320 }
CountDownLatch是通过“共享锁”实现的。下面,我们分析CountDownLatch中3个核心函数: CountDownLatch(int count), await(), countDown()。
尚学堂给同学们带来全新的Java300集课程啦!java零基础小白自学Java必备优质教程_手把手图解学习Java,让学习成为一种享受_哔哩哔哩_bilibili尚学堂给同学们带来全新的Java300集课程啦本课程为Java300集2022版第一季,配合最新版的Java课程,所有视频重新录制,课件所有图形做了重新绘制和配色,图解学习Java,让学习成为一种享受本套教程专门为零基础学员而制,适合准备入行Java开发的零基础学员,视频中穿插多个实战项目。每一个知识点都讲解的通俗易懂,由浅入深。不仅适用于零基础的初学者,有经验的程序员也可做巩固学习。后续课https://www.bilibili.com/video/BV1qL411u7eE?spm_id_from=333.999.0.0
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)