package xyz.jangle.thread.test.n2_4.lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.StampedLock;
/**
* 比较可重入锁和不可重入锁的差别。
* @author Administrator
*
*/
public class M3 {
private static ReentrantLock lock = new ReentrantLock();
private static StampedLock lock2 = new StampedLock();
private static int i = 0;
public static void main(String[] args) {
test();
// test2();
}
private static void test() {
lock.lock();
try {
System.out.println("123");
if(i++ < 10) {
test(); //可重入锁,可以重复调用lock()方法。
}
} finally {
lock.unlock();
}
}
private static void test2() {
long stamp = lock2.writeLock();
try {
System.out.println("123");
if(i++ < 10)
test2(); //此处会死锁,一直等待lock2释放锁
} finally {
lock2.unlockWrite(stamp);
}
}
}