使用AQS实现 独占锁 Mutex

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/yuzhiyun3536/article/details/77977405

Lock

想要弄懂lock的原理,就得首先理解AQS,理解之前,先学会使用它。
首先记住两个要点:
1、AQS内部使用一个int成员变量代表同步状态
2、AQS通过内置的FIFO队列来完成线程的排队工作

Mutex

“`
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class Mutex implements Lock {

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 {
    // TODO Auto-generated method stub
    return sync.tryAcquireNanos(1, unit.toNanos(time));
}

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

@Override
public Condition newCondition() {
    // TODO Auto-generated method stub
    return sync.new ConditionObject();
}

private static class Sync extends AbstractQueuedSynchronizer {

    //判断线程是否占用锁
    @Override
    protected boolean isHeldExclusively() {
        return 1 == getState();
    }

    @Override
    protected boolean tryAcquire(int arg) {
        //compareAndSetState(expect, update)
        if(compareAndSetState(0, 1)) {
            setExclusiveOwnerThread(Thread.currentThread());
            return true;
        }else {
            return false;
        }
    }

    @Override
    protected boolean tryRelease(int arg) {
        if (getState()==1) 
            throw new IllegalMonitorStateException();
        setState(0);
        setExclusiveOwnerThread(null);
        return true;
    }
}

}

参考自

Java 并发编程艺术

展开阅读全文

没有更多推荐了,返回首页