oneshotlatch.java

来自「java concurrency in practice 源码. JAVA」· Java 代码 · 共 39 行

JAVA
39
字号
package net.jcip.examples;import java.util.concurrent.locks.*;import net.jcip.annotations.*;/** * OneShotLatch * <p/> * Binary latch using AbstractQueuedSynchronizer * * @author Brian Goetz and Tim Peierls */@ThreadSafepublic class OneShotLatch {    private final Sync sync = new Sync();    public void signal() {        sync.releaseShared(0);    }    public void await() throws InterruptedException {        sync.acquireSharedInterruptibly(0);    }    private class Sync extends AbstractQueuedSynchronizer {        protected int tryAcquireShared(int ignored) {            // Succeed if latch is open (state == 1), else fail            return (getState() == 1) ? 1 : -1;        }        protected boolean tryReleaseShared(int ignored) {            setState(1); // Latch is now open            return true; // Other threads may now be able to acquire        }    }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?