java除了使用关键字synchronized外,还可以使用ReentrantLock实现独占锁的功能。而且ReentrantLock相比synchronized而言功能更加丰富,使用起来更为灵活,也更适合复杂的并发场景。这篇文章主要是从使用的角度来分析一下ReentrantLock。
spring redis lock里有对ReentrantLock的使用,org.springframework.integration.redis.util.RedisLockRegistry,有兴趣可以看一下它的源码。
一 isFair()方法用来判断lock锁是公平锁还是非公平锁
public class ServiceIsFair { public ReentrantLock lock; public ServiceIsFair(Boolean isFair) { this.lock = new ReentrantLock(isFair); } public void serviceMethod(){ try { lock.lock(); System.out.println("公平锁情况:"+lock.isFair()); } finally { lock.unlock(); } } }
二 lock.isHeldByCurrentThread()的作用是查询当前线程是否保持此锁定,与lock.hasQueueThread()不同的地方是:lock.hasQueueThread(Thread thread)的作用是判断当前线程是否处于等待lock的状态
public class ServiceIsHeldByCurrentThread { private ReentrantLock lock; public ServiceIsHeldByCurrentThread(Boolean isFair) { this.lock = new ReentrantLock(isFair); } public void serviceMethod(){ try { System.out.println("lock.isHeldByCurrentThread() "+lock.isHeldByCurrentThread()); lock.lock(); System.out.println("lock.isHeldByCurrentThread() "+lock.isHeldByCurrentThread()); } finally { lock.unlock(); } } }
三 lock.isLocked()的作用是查询此锁定是否由任意线程保持
public class ServiceIsLocked { private ReentrantLock lock; public ServiceIsLocked(Boolean isFair) { this.lock = new ReentrantLock(isFair); } public void serviceMethod(){ try { System.out.println("lock.isLocked() "+lock.isLocked()); lock.lock(); System.out.println("lock.isLocked() "+lock.isLocked()); } finally { lock.unlock(); } } }
原文链接:https://www.cnblogs.com/lori/p/13539489.html