实现AQS的帮助类(自己实现的加锁类)

public class MyLock2 implements Lock{

    private Helper helper=new Helper();

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

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

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

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

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

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

    private class Helper extends AbstractQueuedSynchronizer{
        //有一种特殊情况,如果当前进来的线程跟当前保存的线程是同一线程则允许拿到锁
        @Override
        protected boolean tryAcquire(int arg) {
            int state=getState();
            Thread t=Thread.currentThread();
            if(state==0){
                if(compareAndSetState(0,arg)){
                    setExclusiveOwnerThread(t);
                    return true;
                }
            }else if(getExclusiveOwnerThread()==t){  //判断进入的线程是否是当前保存的锁
                setState(state+1);
                return true;
            }
            return false;
        }

        @Override
        protected boolean tryRelease(int arg) {
            if(Thread.currentThread()!=getExclusiveOwnerThread()){
                throw new RuntimeException();
            }
            int state=getState()-arg;
            boolean flag=false;
            if(state==0){
                setExclusiveOwnerThread(null);
                flag=true;
            }
            setState(state);
            return flag;
        }

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

测试是否能够进行锁重入

public class Main {
    private  int value;
    private MyLock2 myLock2=new MyLock2();
    public int getValue(){
        myLock2.lock();
        try {
            Thread.sleep(1000);
            return value++;
        } catch (InterruptedException e) {
            throw new RuntimeException();
        }finally {
            myLock2.unlock();
        }
    }

    public void getValue1(){
        myLock2.lock();
        System.out.println("调用方法getValue1");
        getValue2();
        myLock2.unlock();
    }
    public void getValue2(){
        myLock2.lock();
        System.out.println("调用方法getValue2");
        myLock2.unlock();
    }

    public static void main(String[] args){
        Main m=new Main();
        new Thread(new Runnable() {
            @Override
            public void run() {
                m.getValue1();
            }
        }).start();
    }
}

Yfangliang
0 声望1 粉丝