我有以下课程
public class LockTester implements Runnable{
private static Locker locker = new Locker();
public static void main(String[] args){
for(int i=0;i<10;i++){
Thread t = new Thread(new LockTester());
t.start();
}
}
public void run(){
for(int i=0;i<1000;i++){
locker.unlockFirst();//note unlocking here
locker.lockFirst();
locker.lockSecond();
locker.unlockSecond();
locker.unlockFirst();
}
}
}
和储物柜类
public class Locker{
private Lock lock1 = new ReentrantLock();
private Lock lock2 = new ReentrantLock();
public void lockFirst(){
lock1.lock();
}
public void lockSecond(){
lock2.lock();
}
public void unlockFirst(){
if(lock1.tryLock()){//note change
lock1.unlock();
}
}
public void unlockSecond(){
lock2.unlock();
}
}
为什么运行此代码会导致死锁.
解决方法:
lock1被锁定两次:一次在lockFirst中,一次在unlockFirst(lock1.tryLock())中,但是在unlockFirst中仅被解锁一次.
ReentrantLock具有保留计数.请参阅ReentrantLock.如果调用tryLock,即使它已被当前线程保持,它仍会增加保持计数.因此,您将其递增两次,但仅递减一次.