Java基础--CountDownLatch

CountDownLatch是线程同步辅助类,它允许一个或多个线程wait直到countdown被调用使count为0。

CountDownLatch是在java1.5被引入,存在于java.util.concurrent包下。

常用于

1:用于在一个线程中等待N个线程完成

2:让N个子线程同时开始run

方法:

CountDownLatch(int count)   构造器,初始化次数

void await() throws InterruptedException  使一个线程wait,直到count为0

boolean await(long timeout, TimeUnit unit)   使一个线程wait,直到count为0或等待时间timeout

void countDown()   count减一

long getCount()     返回当前count

String toString()    返回当前对象及当前count

 

例子:

-----------------

 1 class Driver {
 2     void main() throws InterruptedException {
 3         CountDownLatch startSignal = new CountDownLatch(1); // 使线程同时开始
 4         CountDownLatch doneSignal = new CountDownLatch(10); // 全部结束
 5 
 6         // create and start threads
 7         for (int i = 0; i < 10; ++i) {
 8             new Thread(new Worker(startSignal, doneSignal)).start();
 9         }
10         
11         // let all threads proceed
12         startSignal.countDown();
13 
14         // wait for all to finish
15         doneSignal.await();
16     }
17 }
18 
19 class Worker implements Runnable {
20     private final CountDownLatch startSignal;
21     private final CountDownLatch doneSignal;
22 
23     Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
24         this.startSignal = startSignal;
25         this.doneSignal = doneSignal;
26     }
27 
28     public void run() {
29         try {
30             //wait the start signal
31             startSignal.await();
32             doWork();
33             doneSignal.countDown();
34         } catch (InterruptedException ex) {
35         }
36     }
37 
38     void doWork() {
39     }
40 }

----------------- 

实现:

AQS静态内部类实现的同步控制

private static final class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = 4982264981922014374L;

        Sync(int count) {
            setState(count);
        }

        int getCount() {
            return getState();
        }

        protected int tryAcquireShared(int acquires) {
            return (getState() == 0) ? 1 : -1;
        }

        protected boolean tryReleaseShared(int releases) {
            // Decrement count; signal when transition to zero
            for (;;) {
                int c = getState();
                if (c == 0)
                    return false;
                int nextc = c-1;
                if (compareAndSetState(c, nextc))
                    return nextc == 0;
            }
        }
    }
View Code

end

原文地址:https://www.cnblogs.com/luangeng/p/6036517.html