【发布时间】:2012-05-10 20:25:04
【问题描述】:
难道不是在一个线程中的 wait() 之前调用另一个线程中的 notify() 吗? 这发生在我身上。
客户端从目标请求一个值并等待结果变量 RV。 如果目标是客户端本身,我会使用正确的结果更新 RV,并在另一个线程中调用 RV 上的 notify()。
class EMU {
ResultVar RV;
Address my_address;
ResultVar findValue(String key) {
String tgt = findTarget(key);
sendRequest(tgt, key);
synchronized(RV) {
RV.wait();
}
return RV;
}
Runnable Server = new Runnable() {
public void run() {
//code to receive connections. Assume object of type Request is read from the stream.
Request r = (Request) ois.readObject();
if(r.requesterAddr.compareTo(my_address) == 0) {
String val = findVal(key);
RV.putVal(val);
synchronized(RV){
RV.notify();
}
}
}
};
}
问题在于,在请求者与自己完成所有“联网”(上例中的sendReqest)之前,结果变量中的结果已更新。当请求者线程现在调用 wait() 时,程序不会继续,因为已经调用了 notify。
我们该如何预防?
【问题讨论】:
-
In case the target is the client itself你是什么意思?你能放一些代码示例吗? -
@shishir garg 你能粘贴一些代码吗
-
没有看到代码很难回答 - 虽然有 2 个 cmets:a) 通常最好使用 notifyAll 而不是 notify,除非您知道自己在做什么 b) 可以使用 wait 和 notify容易出错,除非您需要非常具体的东西,否则您应该使用更高级别的并发 API。
标签: java multithreading wait notify