可重置的倒计时锁

可重置的倒计时锁,第1张

重置的倒计时锁

我复制

CountDownLatch
并实现了
reset()
一种将内部
Sync
类重置为其初始状态(开始计数)的方法:)看起来可以正常工作。不再需要创建不必要的对象
o /因为
sync
私有的,所以无法进行子类化。嘘

import java.util.concurrent.CyclicBarrier;import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.AbstractQueuedSynchronizer;public class ResettableCountDownLatch {        private static final class Sync extends AbstractQueuedSynchronizer {        private static final long serialVersionUID = 4982264981922014374L;        public final int startCount;        Sync(int count) { this.startCount = count; setState(startCount);        }        int getCount() { return getState();        }        public int tryAcquireShared(int acquires) { return getState() == 0? 1 : -1;        }        public 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; }        }        public void reset() {  setState(startCount);        }    }    private final Sync sync;        public ResettableCountDownLatch(int count) {        if (count < 0) throw new IllegalArgumentException("count < 0");        this.sync = new Sync(count);    }        public void await() throws InterruptedException {        sync.acquireSharedInterruptibly(1);    }    public void reset() {        sync.reset();    }        public boolean await(long timeout, TimeUnit unit)        throws InterruptedException {        return sync.tryAcquireSharedNanos(1, unit.tonanos(timeout));    }        public void countDown() {        sync.releaseShared(1);    }        public long getCount() {        return sync.getCount();    }        public String toString() {        return super.toString() + "[Count = " + sync.getCount() + "]";    }}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5165019.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-18
下一篇2022-11-18

发表评论

登录后才能评论

评论列表(0条)

    保存