公平锁和非公平锁

公平锁: Threads acquire a fair lock in the order in which they requested it
非公平锁: a nonfair lock permits barging: threads requesting a lock can jump ahead of the queue
of waiting threads if the lock happens to be available when it is requested.

所谓公平锁指的是哪个线程先运行,那就可以先得到锁。
非公平锁是不管线程是否是先运行,上来就直接尝试占有锁,如果尝试失败,就再采用类似公平锁那种方式。

我们看下ReentrantLock 类的源码:

公平锁代码:

 protected final boolean tryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            //状态为0,说明当前没有线程占有锁
            if (c == 0) {
               //判断当前队列前面是有等待线程 ,没有的话尝试做cas操作,有点话就等待
                if (!hasQueuedPredecessors() &&
                    compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
           //判断当前获得锁的线程是否为自己,这里体现出了 可重入锁的机制
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0)
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }

非公平锁代码:

/**
         * Performs non-fair tryLock.  tryAcquire is implemented in
         * subclasses, but both need nonfair try for trylock method.
         */
        final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            ////状态为0,说明当前没有线程占有锁
            if (c == 0) {
                //上来就直接尝试占有锁
                if (compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值