实现一个独占锁

129 阅读1分钟

基于AQS这个类

public class MyLock implements Lock, java.io.Serializable {

    class MySync extends AbstractQueuedSynchronizer {
        @Override
        protected boolean tryAcquire(int arg) {
            if (compareAndSetState(0,arg)){   ##<1>
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

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

        @Override
        protected boolean isHeldExclusively() {
            return getExclusiveOwnerThread()==Thread.currentThread();
        }

    }

  private AbstractQueuedSynchronizer abstractQueuedSynchronizer =new MySync();

    @Override
    public void lock() {
        abstractQueuedSynchronizer.acquire(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

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

    @Override
    public Condition newCondition() {
        return null;
    }

    public static void main(String[] args) {
        MyLock myLock = new MyLock();
        Thread thread = new Thread(() -> {
            myLock.lock();
            System.out.println("hello,world,俺是1");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                myLock.unlock();
            }
        });
        Thread thread2 = new Thread(() -> {
            myLock.lock();
            System.out.println("hello,world,我是2");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                myLock.unlock();
            }
        });
        thread.start();
        thread2.start();
    }
}

<1>是实现独占锁的关键,也就是使用了CAS机制,去更新AQS中维护的一个公共变量State,根据state的大小去判断是否有进程获取到锁。 CAS的实现逻辑如下: