/**
 *@Desc
 * 这个自定义的独占锁 只是一个简单的版本,非常粗糙,只为了加深对AQS原理理解。但还有一些列问题有待解决,比如锁的重入,锁不允许被其他线程中断等!
 *@Author zhangfengshi
 *@Date 2021/4/1 7:24 下午
 *@Version 1.0
 */
public class MutiLock implements Lock {


    public  class Sync extends AbstractQueuedSynchronizer{

        //是否处于独占状态
        @Override
        public boolean isHeldExclusively(){
            return getState()==1;//访问或修改同步状态
        }
        //获取锁
        @Override
        public boolean tryAcquire(int arg){
            if(compareAndSetState(0,1)){
                //设置当前线程拥有独占访问权
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }
        //释放锁
        @Override
        public boolean tryRelease(int arg){
            //已经释放就抛异常
            if(getState()==0){
                throw  new IllegalMonitorStateException();
            }
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }

        public Condition newCondition(){
            return new ConditionObject();
        }
    }

    public Sync sync=new Sync();
    @Override
    public void lock() {
        sync.acquire(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    @Override
    public boolean tryLock() {
        return sync.tryAcquire(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(time));
    }

    @Override
    public void unlock() {
        sync.tryRelease(1);
    }

    @Override
    public Condition newCondition() {
        return sync.newCondition();
    }

    public boolean isLock(){
        return sync.isHeldExclusively();
    }
}

 

相关文章:

  • 2021-05-01
  • 2023-03-04
  • 2021-06-20
  • 2021-04-07
  • 2021-12-08
  • 2022-12-23
  • 2021-07-09
  • 2021-07-12
猜你喜欢
  • 2021-08-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-18
  • 2021-09-27
  • 2021-06-24
相关资源
相似解决方案