ReentrantLock l = new ReentrantLock(true);
Reader[] readers = new Reader[2];
for (int i = 0; i < readers.length; i++) {
readers[i] = new Reader(l);
}
for (int i = 0; i < readers.length; i++) {
readers[i].start();
}
public class Reader extends Thread {
private ReentrantLock l;
public Reader(ReentrantLock l) {
this.l = l;
}
@Override
public void run() {
try {
l.tryLock();
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " i = " + i);
Thread.sleep(500);
}
// l.unlock(); // although it commented the code not hanged why?
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
according to my understanding to tryLock() Acquires the lock if it is not held by another thread and returns immediately now in my case i have two threads suppose thread_0 get lock now i have two questions : Q1: why thread_1 still enter the critical section after l.tryLock() isn't it locked by thread_0; Q2: isn't it supposes to my code to be hanged because thread_0 doesn't release the lock #thanks advance