如果線程A訪問線程B的方法,恰好在等待一個條件,線程A會被卡住在該方法中嗎?我怎麼能這樣做,線程A可以實際檢查線程B是否正在等待條件,並因此被條件暫停,並在線程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對象是餵養另一個,從而被卡在一個爭用條件。
謝謝!