【问题标题】:Can CountDownLatch be implemented using an exclusive lock?CountDownLatch 可以用排他锁来实现吗?
【发布时间】:2018-11-20 12:48:25
【问题描述】:

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");

}

}

【问题讨论】:

  • 你没有附加任何代码
  • 请提供您代码的相关部分。添加一个Minimal, Complete, and Verifiable example,包括正确的示例输入/输出数据。
  • 错误 404:找不到代码。
  • 我已经提交了我的代码。谢谢

标签: java concurrency java.util.concurrent


【解决方案1】:

好吧,shared lock 的意思是,您可以有超过 1 个线程等待完成。如果您使用exclusive lock 实现它,那么您将只能等待 1 个线程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    相关资源
    最近更新 更多