I am writing the code below to check when a thread will be awake, when it is waiting for an object Condition.
- But I believe that I need to unlock after I call
signal(). A lock is not released by this method, while await () will release this lock.
This is from condition # expectation
The lock associated with this condition is atomically released , and the current thread is disabled for thread planning purposes and is at rest until one of four things happens:
And this is from Conditon # signal
Awakens one waiting thread.
If any threads are waiting for this condition, then one of them will be selected for awakening. Then this thread must re-capture the lock before returning from the wait.
But in my code this is not so until we unlock the lock. Why is this so? Since, in my opinion, when we decide to signal to others, we no longer have to hold the lock, right?
Since we can do many things between calls signaland unlocklet's say I sleep 10 seconds, what exactly is the java time signaling another thread? Is there any other background thread that works between us signaland unlock?
public class WorkerThread extends Thread{
@Override
public void run() {
Monitor.lock.lock();
while (!Monitor.isConditionTrue){
try {
Monitor.condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("THREAD ID "+this.getId()+"-------working --------");
System.out.println("------singnall--------");
Monitor.isConditionTrue=true;
Monitor.condition.signal();
try {
Thread.sleep(3000);
System.out.println("------unlock--------");
Monitor.lock.unlock();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Monitor {
static ReentrantLock lock = new ReentrantLock();
static Condition condition = lock.newCondition();
static volatile boolean isConditionTrue = true;
public static void main(String args[]) {
Thread t1 = new WorkerThread();
Thread t2 = new WorkerThread();
t1.start();
t2.start();
Thread.sleep(2000);
lock.lock();
isConditionTrue=true;
condition.signalAll();
lock.unlock();
}
}
CONCLUSION:
THREAD ID 9
THREAD ID 10
source
share