手写一个简易的ReentrantLock

public class HqaLock {
    private static final Unsafe unsafe = reflectGetUnsafe();
    private static final long ownerOffset;

    /**
     * 锁是否被持有(1)是,(0)否
     */
    AtomicInteger state = new AtomicInteger(0);
    /**
     * 当前持有锁的线程
     */
    volatile Thread owner = new Thread();
    /**
     * 线程等待池
     */
    private Queue<Thread> waitQueue = new LinkedBlockingQueue();
    /**
     * 重入次数
     */
    AtomicInteger reentrantCount = new AtomicInteger(0);

    private static Unsafe reflectGetUnsafe() {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            return (Unsafe) field.get(null);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    static {
        try {
            ownerOffset = unsafe.objectFieldOffset
                    (HqaLock.class.getDeclaredField("owner"));
        } catch (Exception ex) { throw new Error(ex); }
    }

    public void lock(){
        //未被持有则直接获取锁
        if (state.get() == 0){
            //自旋cas改变锁状态
            for(;;){
                boolean b = state.compareAndSet(0,1);
                if (b == true){
                    unsafe.compareAndSwapObject(this,ownerOffset,owner,Thread.currentThread());
                    owner = Thread.currentThread();
                    reentrantCount.set(1);
                    break;
                }
            }

        }else {//已经被持有
            //持有锁的线程是是自己
            if (unsafe.getObject(owner,ownerOffset) == Thread.currentThread()){
                reentrantCount.getAndAdd(1);
            }else {
                waitQueue.add(Thread.currentThread());
                //持有锁的线程不是自己
                while (true){
                    //阻塞休眠
                    LockSupport.park();
                    //如果锁被持有者释放了
                    if (state.get() == 0){
                        owner = Thread.currentThread();
                        state.set(1);
                        break;
                    }
                }
            }
        }
    }

    public void unlock() throws Exception {

        if (unsafe.getObject(this,ownerOffset) != Thread.currentThread()){
            throw new Exception("该线程未持有锁");
        }
        //重入次数减1
        reentrantCount.getAndDecrement();
        //直到重入锁全部解开的才能真正的解锁
        if (reentrantCount.get() == 0){
            state.set(0);
            Thread head = waitQueue.peek();
            LockSupport.unpark(head);
        }

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值