Java多线程深入学习-ReentrantLock源码解析

1.类定义

/**
 * 基于AQS的可重入锁  可定义公平与非公平
 */
public class ReentrantLock implements Lock, java.io.Serializable {
}

2.ReentrantLock中的同步器

public class ReentrantLock implements Lock, java.io.Serializable {
    private static final long serialVersionUID = 7373984872572414699L;
    private final Sync sync;

    /** 定义抽象静态内部类Sync继承抽象类AbstractQueuedSynchronizer */
    abstract static class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = -5179523762034025860L;
        abstract void lock();
        /** 非公平的尝试获取锁 */
        final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();	//当前线程
            int c = getState();	//当前状态
            if (c == 0) {	//锁还未同步
                if (compareAndSetState(0, acquires)) {	//将State修改为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);	//设置State值
                return true;	//获取锁成功
            }
            return false;	//获取锁失败
        }
        /**
         * 尝试释放
         */
        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;	//完全释放  设置值为true
                setExclusiveOwnerThread(null);	//设置加锁线程为null
            }
            setState(c);	//设置状态
            return free;	//返回是否完全释放
        }
        /** 判断是否为当前线程持有锁 */
        protected final boolean isHeldExclusively() {
            return getExclusiveOwnerThread() == Thread.currentThread();
        }
        /** 创建一个ConditionObject对象 */
        final ConditionObject newCondition() {
            return new ConditionObject();
        }
        /** 获取锁的当前持有线程 */
        final Thread getOwner() {
            return getState() == 0 ? null : getExclusiveOwnerThread();
        }
        /** 获取锁的重入次数 */
        final int getHoldCount() {
            return isHeldExclusively() ? getState() : 0;
        }
        /** 当前锁是否被使用 */
        final boolean isLocked() {
            return getState() != 0;
        }
        private void readObject(java.io.ObjectInputStream s)
            throws java.io.IOException, ClassNotFoundException {
            s.defaultReadObject();
            setState(0);
        }
    }

    /**
     * 定义静态内部类NonfairSync(非公平)继承Sync
     */
    static final class NonfairSync extends Sync {
        private static final long serialVersionUID = 7316153563782823691L;
        final void lock() {
            if (compareAndSetState(0, 1))	//修改status为1
                setExclusiveOwnerThread(Thread.currentThread());	//记录当前线程
            else
                acquire(1);	//获取独占锁,对中断不敏感
        }
        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
    }

    /**
     * 定义静态内部类FairSync(公平)继承Sync
     */
    static final class FairSync extends Sync {
        private static final long serialVersionUID = -3000897897090466540L;
        final void lock() {
            acquire(1);
        }
        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;
        }
    }
}

3.构造方法-指定同步器类型并初始化同步器

    /**
     * 构造方法  默认sync赋值非公平的NonfairSync实现
     */
    public ReentrantLock() {
        sync = new NonfairSync();
    }

    /**
     * 构造方法  根据入参初始化sync赋值
     */
    public ReentrantLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
    }

4.方法实现-调用同步器方法进行操作处理

    /**
     * 加锁
     */
    public void lock() {
        sync.lock();
    }

    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    /**
     * 尝试获取锁 获取失败返回false
     */
    public boolean tryLock() {
        return sync.nonfairTryAcquire(1);
    }

    /**
     * 尝试获取锁
     */
    public boolean tryLock(long timeout, TimeUnit unit)
            throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(timeout));
    }

    /**
     * 释放锁
     */
    public void unlock() {
        sync.release(1);
    }

    /** 创建一个ConditionObject对象 */
    public Condition newCondition() {
        return sync.newCondition();
    }

    /** 获取锁的重入次数 */
    public int getHoldCount() {
        return sync.getHoldCount();
    }

    /** 判断是否为当前线程持有锁 */
    public boolean isHeldByCurrentThread() {
        return sync.isHeldExclusively();
    }

    /** 判断当前锁是否被占用 */
    public boolean isLocked() {
        return sync.isLocked();
    }

    /** 判断当前锁是否公平锁 */
    public final boolean isFair() {
        return sync instanceof FairSync;
    }

    /** 获取占有当前锁的线程 */
    protected Thread getOwner() {
        return sync.getOwner();
    }

    /** 等待队列中是否还有线程  */
    public final boolean hasQueuedThreads() {
        return sync.hasQueuedThreads();
    }

    /** 线程是否在等待队列中  */
    public final boolean hasQueuedThread(Thread thread) {
        return sync.isQueued(thread);
    }

    /** 获取等待队列长度 */
    public final int getQueueLength() {
        return sync.getQueueLength();
    }

    /** 获取等待队列中的所有线程 */
    protected Collection<Thread> getQueuedThreads() {
        return sync.getQueuedThreads();
    }

    /** 获取condition.await中是否有数据 */
    public boolean hasWaiters(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

    /** 获取condition.await中的线程数量 */
    public int getWaitQueueLength(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

    /** 获取condition.await中的线程 */
    protected Collection<Thread> getWaitingThreads(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

猜你喜欢

转载自blog.csdn.net/luo_mu_hpu/article/details/107743255