144 多執行緒 執行緒間通訊 等待喚醒機制

2021-09-02 12:42:19 字數 1261 閱讀 8437

class res

class input implements runnable

public void run()catch(exception e){}

if(x==0)

else

x = (x+1)%2;

r.flag = true;

r.notify();}}

}}class output implements runnable

public void run()catch(exception e){}

system.out.println(r.name+"--"+r.***);

r.flag = false;

r.notify();}}

}}class inputoutput}/*

wait();notify();notifyall();

都使用在同步中,因為要對持有監視器(鎖)的執行緒中操作。

所以要使用在同步中,因為只有同步才具有鎖。

為什麼這些操作執行緒的方法要定義在object類中呢?

因為這些方法在操作同步的執行緒時,都必須要標識它們所操作

執行緒持有的鎖。只有同乙個鎖上的被等待執行緒,可以被同乙個鎖上的

notify喚醒。不可以對不同鎖中的執行緒進行喚醒。

也就是說,等待和喚醒必須是同乙個鎖。

而鎖可以是任意物件,所以可以被任意物件呼叫的方法定義在object

類中。*/

**優化

class rescatch(exception e){}

}this.name = name;

this.*** = ***;

flag = true;

this.notify();

}public synchronized void out()catch(exception e){}

}system.out.println(name+"--"+***);

flag = false;

this.notify();}}

class input implements runnable

public void run()

else

x = (x+1)%2;}}

}class output implements runnable

public void run()}}

class inputoutput

}

Java 多執行緒間的通訊 等待喚醒

有兩個執行緒 乙個給名字和性別賦值 input 乙個輸出名字和性別 output 但會一下輸出很多同樣的名字和性別 cpu沒切走 用等待喚醒機制 就可以 1 賦值乙個 然後input wait 喚醒output 2 輸出乙個 output wait 再喚醒input這樣可以賦值乙個 就輸出乙個等待 ...

執行緒間通訊 等待喚醒機制

執行緒間通訊 其實就是多個執行緒在操作同乙個資源,但是操作的動作不同 class res2 class input2 implements runnable public void run catch interruptedexception e if x 0 else x x 1 2 r.flag...

多執行緒間的通訊之等待喚醒機制

執行緒間的通訊 其實就是多個執行緒在操作同乙個資源。但是操作動作不同 例子 需求 模擬簡單賣票系統 輸入乙個人,緊接著輸出乙個人 出現了安全問題 輸出了麗麗 man 同步後class res 雖然安全 問題解決了,但並沒出現我們想要的一男一女交替的情景 這是就引進一種方法 等待喚醒機制 都使用在同步...