ReentrantLock - JiyangM/spring GitHub Wiki
ReentrantLock 是可重入的互斥锁。
方法:
- lock :获取锁,如果锁被占用,则等待。
- lockInterruptibly:获取锁,优先响应中断。
- tryLock:尝试获得锁,如果成功,返回true,如果失败返回false,立即返回。
- unLock :释放锁。
注意事项:
- 一定要在finally中释放锁。
demo
lock.lock();
try {
// remove the ole cookie if there has had one
cookieJar.remove(cookie);
// add new cookie if it has a non-zero max-age
if (cookie.getMaxAge() != 0) {
URI effectiveURI = getEffectiveURI(uri);
cookieJar.put(cookie, effectiveURI);
// and add it to domain index
if (cookie.getDomain() != null) {
addIndex(domainIndex, cookie.getDomain(), cookie);
}
// add it to uri index, too
addIndex(uriIndex, effectiveURI, cookie);
}
} finally {
lock.unlock();
}
可重入锁?
自己可以再次获取自己的内部锁。
synchronized 和 ReentrantLock 都是重入锁!
public class OptionT {
public void method1() {
synchronized (OptionT.class) {
System.out.println("方法1获得ReentrantTest的锁运行了");
method2();
}
}
public void method2() {
synchronized (OptionT.class) {
System.out.println("方法1里面调用的方法2重入锁,也正常运行了");
}
}
public static void main(String[] args) {
new OptionT().method1();
}
}
输出
方法1获得ReentrantTest的锁运行了
方法1里面调用的方法2重入锁,也正常运行了
public class OptionT {
private Lock lock = new ReentrantLock();
public void method1() {
lock.lock();
try {
System.out.println("方法1获得ReentrantLock锁运行了");
method2();
} finally {
lock.unlock();
}
}
public void method2() {
lock.lock();
try {
System.out.println("方法1里面调用的方法2重入ReentrantLock锁,也正常运行了");
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
new OptionT().method1();
}
}
方法1获得ReentrantLock锁运行了
方法1里面调用的方法2重入ReentrantLock锁,也正常运行了
synchronized 和 ReentrantLock比较
- 都是可重入锁
- synchronized 不会产生死锁,ReentrantLock需要在finally中释放锁
- ReentrantLock 具有公平锁还有非公平锁的实现。(公平锁耗时)
- ReentrantLock 可以知道有没有成功获取锁
- Lock可以让等待锁的线程响应中断