为什么以下非常简单的代码不起作用..它卡住了..我正在尝试使用显式锁java.util.concurrent.locks.ReentrantLock;
及其newCondition()
方法。
这是我的代码:
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();
}
}
}
我正在锁定同一个锁,所以它应该可以工作......相反,当它调用时它在主线程中被阻塞incrementVariable()
。为什么会发生这样的事情?提前致谢。