[問題] 猛虎一書第 18 題
class Computation extends Thread{
private int num;
private boolean isComplete;
private int result;
public Computation(int num)
{this.num = num;}
public synchronized void run(){
result = num * 2;
isComplete = true;
System.out.println(result +" notify()");
notify();
}
public synchronized int getResult(){
while(!isComplete)
{
try{
System.out.println("wait()");
wait();
}catch(InterruptedException e){}
}
return result;
}
public static void main(String[] args){
Computation[] computations = new Computation[4];
for(int i = 0;i< computations.length;i++)
{
computations[i] = new Computation(i);
computations[i].start();
}
for(Computation c: computations)
System.out.println(c.getResult()+ " ");
}
}
正確答案是 會run出 0 2 4 6
我想問的是,為什麼在getResult的時候 如果result還沒好,進入wait()
怎麼確定是他要的那個答案會來notify()
例如我現在computations[1]要getResult, 然後wait()
那如果computations[2]比computations[1]還快做完然後call notify()
這樣不就亂了?
可是我實際上跑這個程式時 不會出現這個狀況
雖然四個thread不一定是依序跑完
可是就是怎樣都不會出現我說的那個情況
由不同的thread來notify result
不好意思,不知道這樣大家看的懂嗎
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.230.84.24
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):