CountDownLatch可以使用排他锁实现吗?

时间:2018-11-20 12:48:25

标签: java concurrency java.util.concurrent

JDK1.8的源代码由AQS共享锁实现。使用共享锁有哪些注意事项?为什么不使用排他锁?下面的附件是我的排他锁实现的代码:

public class MyCountDownLatch {
private static final class Sync extends AbstractQueuedSynchronizer {
    Sync(int count) {
        setState(count);
    }
    int getCount() {
        return getState();
    }
    protected boolean tryAcquire(int acquires) {
        return (getState() == 0) ? true :false;
    }
    protected boolean tryRelease(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;
        }
    }
}
private final MyCountDownLatch.Sync sync;
public MyCountDownLatch(int count) {
    this.sync = new MyCountDownLatch.Sync(count);
}
public void await() throws InterruptedException {
    sync.acquireInterruptibly(1);
}
public void countDown() {
    sync.release(1);
}
public static void main(String[] args) throws InterruptedException {
    MyCountDownLatch myCountDownLatch = new MyCountDownLatch(5);
    for(int i=0;i<5;i++){
        new Thread(()-> {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"start");
            myCountDownLatch.countDown();
        }).start();
    }
    myCountDownLatch.await();
    System.out.println("finished");

}

}

1 个答案:

答案 0 :(得分:0)

好吧,shared lock意味着您可以有1个以上的线程等待完成。如果使用exclusive lock来实现,那么只能等待1个线程。