I have the following class
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();
}
}
}
and Locker class
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();
}
}
Why does running this code result in deadlock.