可重入性质和源码解析

package lock.reentrantlock;

import java.util.concurrent.locks.ReentrantLock;

public class GetHoldCount {
    private  static ReentrantLock lock =  new ReentrantLock();

    public static void main(String[] args) {
        System.out.println(lock.getHoldCount());
        lock.lock();
        System.out.println(lock.getHoldCount());
        lock.lock();
        System.out.println(lock.getHoldCount());
        lock.lock();
        System.out.println(lock.getHoldCount());
        lock.unlock();
        System.out.println(lock.getHoldCount());
        lock.unlock();
        System.out.println(lock.getHoldCount());
        lock.unlock();
        System.out.println(lock.getHoldCount());
    }
}
package lock.reentrantlock;

import java.util.concurrent.locks.ReentrantLock;

public class RecursionDemo {

    private static ReentrantLock lock = new ReentrantLock();

    private static void accessResource() {
        lock.lock();
        try {
            System.out.println("已经对资源进行了处理");
            if (lock.getHoldCount()<5) {
                System.out.println(lock.getHoldCount());
                accessResource();
                System.out.println(lock.getHoldCount());
            }
        } finally {
            lock.unlock();
        }
    }
    public static void main(String[] args) {
        accessResource();
    }
}

源码对比:可重入锁ReentrantLock以及非可重入锁ThreadPoolExecutor的Worker类 

可重入性质和源码解析_第1张图片

ReentrantLock的其他方法介绍

  • isHeldByCurrentThread():锁是否被当前线程持有
  • getQueueLength():返回当前正在等待这把锁的队列有多长,一般这两个方法是开发和调试的时候使用,上线后用到的不多

 

 

 

你可能感兴趣的:(可重入性质和源码解析)