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
Your code is entering the critical section because, tryLock() is not a blocking function, it will return true or false immediately, and proceed with the "Critical Section" code snippet below.
In the documentation of tryLock() you can read
So you need to call lock() method, which waits until the lock is released by another reader.