可重入性质和源码解析
package lock.reentrantlock;
import java.util.concurrent.locks.ReentrantLock;
public class GetHoldCount {
privatestatic 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类
文章图片
【可重入性质和源码解析】ReentrantLock的其他方法介绍
- isHeldByCurrentThread():锁是否被当前线程持有
- getQueueLength():返回当前正在等待这把锁的队列有多长,一般这两个方法是开发和调试的时候使用,上线后用到的不多
推荐阅读
- 2019-1-14
- 抑郁症(可怕吗?)
- 松软可口易消化,无需烤箱超简单,新手麻麻也能轻松成功~
- 你不可不知的真相系列之科学
- 关于自我为中心的一点感想
- 为什么孩子一定要学会可视化思维!
- 唐嫣可真会穿,西装搭牛仔裤都能穿出高级感,一双大长腿太抢镜
- 我怀孕了可是我失业了,孕期生活,到底该何去何从()
- 从战略性的角度可以配置股票
- 只要有一台手机,人人都可以是摄影师