java-学习篇-可重入锁(ReentrantLock)

文章目录

概览

package java.util.concurrent.locks;
public class ReentrantLock implements Lock, java.io.Serializable

内部类

ReentrantLock 默认使用非公平锁,也可以通过构造器来显示的指定使用公平锁。

abstract static class Sync extends AbstractQueuedSynchronizer
abstract void lock();// 加锁,子类实现

public abstract class AbstractQueuedSynchronizer
    extends AbstractOwnableSynchronizer
    implements java.io.Serializable
protected boolean tryAcquire(int arg)

// 非公平锁
static final class NonfairSync extends Sync
// 公平锁
static final class FairSync extends Sync

阅读源码可知,公平锁与非公平锁的 lock() 方法唯一的区别就在于公平锁在获取同步状态时多了一个限制条件:hasQueuedPredecessors()。该方法主要判断当前线程是否位于同步队列中的第一个。

public final boolean hasQueuedPredecessors() {
    // The correctness of this depends on head being initialized
    // before tail and on head.next being accurate if the current
    // thread is first in queue.
    Node t = tail; // Read fields in reverse initialization order
    Node h = head;
    Node s;
    return h != t &&
        ((s = h.next) == null || s.thread != Thread.currentThread());
}

方法

构造方法:

public ReentrantLock() {
    sync = new NonfairSync();// 创建非公平锁
}

public ReentrantLock(boolean fair) {
    sync = fair ? new FairSync() : new NonfairSync();
}
public void lock()
public boolean tryLock()
public boolean tryLock(long timeout, TimeUnit unit)
public void unlock()

使用

Lock lock = new ReentrantLock();
lock.lock();
try {
} finally {
    lock.unlock();
}

猜你喜欢

转载自blog.csdn.net/u010019244/article/details/106159754
今日推荐