/** *@Desc 设计一个同步工具,同一时刻最多只有两个线程能访问,超过线程将被阻塞<br> * 思路分析: * 1.共享锁 两个线程及以内能成功获取到锁 * 2. *@Author zhangfengshi *@Date 2021/4/5 3:26 下午 *@Version 1.0 */ public class TwinsLock implements Lock { public Sync sync=new Sync(2); public static class Sync extends AbstractQueuedSynchronizer { public Sync(int count){ if(count<=0){ throw new RuntimeException("error"); } setState(count); } /** * * @param reduceCount * @return -1获取共享锁失败 0-只能成功一次 后续将获取失败 正数-可以获取锁 */ @Override protected int tryAcquireShared(int reduceCount) { for(;;){ int currentCount=this.getState(); int newCount=currentCount-reduceCount; //newCount<0代表currentCount=0 if(newCount<0||compareAndSetState(currentCount,newCount)){ return newCount; } } } @Override protected boolean tryReleaseShared(int returnCount) { for(;;){ int currentCount=this.getState(); int newCount=currentCount+returnCount; if(compareAndSetState(currentCount,newCount)){ return true; } } } } @Override public void lock() { sync.acquireShared(1); } @Override public void unlock() { sync.releaseShared(1); } @Override public void lockInterruptibly() throws InterruptedException { } @Override public boolean tryLock() { int result= sync.tryAcquireShared(1); return result>0; } @Override public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { return false; } @Override public Condition newCondition() { return null; } }