Why the following very simple code does not work.. it gets stuck..
I am trying to use the explicit lock java.util.concurrent.locks.ReentrantLock;
and its newCondition()
method.
Here is my code:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class TheCondition implements Runnable {
ReentrantLock lock = new ReentrantLock();
Condition condition = lock.newCondition();
static int variable = 2;
public void incrementVariable() throws InterruptedException
{
lock.lock();
try{
condition.await();
for (int i = 0;i<100000;i++){
variable++;
}
}
finally
{
lock.unlock();
}
}
public static void main (String []args) throws InterruptedException
{
TheCondition tc = new TheCondition();
Thread t1 = new Thread(tc);
t1.start();
Thread.sleep(1000);
tc.incrementVariable();
t1.join();
System.out.println(variable);
}
public void run()
{
for (int i = 0;i<100000;i++){
variable++;
}
System.out.println(variable);
lock.lock();
try{
condition.signalAll();
}
finally{
lock.unlock();
}
}
}
I am locking on the same lock so it should be working... instead it gets blocked in the main thread when it calls incrementVariable()
.
Why would it happen such a thing?
Thanks in advance.