如果线程A访问线程B的方法,它正好等待条件,那么线程A是否会卡在该方法中?我怎样才能使线程A能够实际检查线程B是否在等待一个条件,因此也会被一个条件暂停,并在线程B的条件完成后发出信号?
基本上,我想知道如何防止嵌套条件阻止调用嵌套调用的父方法(线程间)。
例如:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Person {
final Lock lock = new ReentrantLock();
Condition isFree = lock.newCondition();
State state;
public void eat() throws InterruptedException {
lock.lock();
try {
while (state != State.WAITING) {
isFree.await();
}
//begin eating
state = State.EATING;
Thread.sleep(1000);
state = State.WAITING;
isFree.signal();
} finally {
lock.unlock();
}
}
public void feed(Person person) throws InterruptedException {
lock.lock();
try {
while (state != State.WAITING) {
isFree.await();
}
//begin intention to feed
person.eat();
} finally {
lock.unlock();
}
}
enum State {
EATING, WAITING;
}
}
在上面的例子中,可能会发生每个Person对象正在进行另一个对象,因此会陷入竞争状态。
谢谢!