编程语言
首页 > 编程语言> > ReentrantLock源码之公平锁的实现

ReentrantLock源码之公平锁的实现

作者:互联网

公平锁:所有线程都老老实实排队 
非公平锁:只要有机会,就先尝试抢占资源 
可能导致后面排队等待的线程等不到相应的cpu资源,从而引起线程饥饿
public class ReentrantLockDemo {

    public static void main(String[] args) {
        // 传入参数true,表示获得公平锁的实现
        ReentrantLock reentrantLock = new ReentrantLock(true);
        reentrantLock.lock();
        reentrantLock.unlock();
    }

}
    public void lock() {
        sync.acquire(1);
    }
    public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }
    protected boolean tryAcquire(int arg) {
        throw new UnsupportedOperationException();
    }

标签:reentrantLock,ReentrantLock,tryAcquire,源码,公平,arg,public
来源: https://www.cnblogs.com/chniny/p/16269553.html