[問題] 猛虎一書第 18 題

看板java作者 (ㄟ)時間17年前 (2008/06/19 14:11), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串1/2 (看更多)
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
文章代碼(AID): #18MVYHgk (java)
文章代碼(AID): #18MVYHgk (java)