并发操作之——公平锁和非公平锁的区别以及ReenTrantLock源码

2021/9/11 20:06:52

本文主要是介绍并发操作之——公平锁和非公平锁的区别以及ReenTrantLock源码,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

并发操作

并发操作之——公平锁和非公平锁的区别


并发操作之——公平锁和非公平锁的区别

  • 并发操作
  • 一、公平锁和非公平锁的区别
  • 二、ReenTrantLock源码
  • 总结


一、公平锁和非公平锁的区别

公平锁是先入先出原则,先申请的先加锁,轮流加锁
非公平锁是每个线程都去抢锁,谁抢到锁,谁就加锁。

二、ReenTrantLock源码

非公平锁

     static final class NonfairSync extends Sync {
        private static final long serialVersionUID = 7316153563782823691L;
        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
    }

公平锁

    static final class FairSync extends Sync {
        private static final long serialVersionUID = -3000897897090466540L;
        /**
         * Fair version of tryAcquire.  Don't grant access unless
         * recursive call or no waiters or is first.
         */
        @ReservedStackAccess
        protected final boolean tryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                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;
        }
    }

tryRelease

        protected final boolean tryRelease(int releases) {
            int c = getState() - releases;
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            boolean free = false;
            if (c == 0) {
                free = true;
                setExclusiveOwnerThread(null);
            }
            setState(c);
            return free;
        }

总结

公平锁和非公平锁的区别以及ReenTrantLock源码



这篇关于并发操作之——公平锁和非公平锁的区别以及ReenTrantLock源码的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程