class a { int a=1; synchronized void A() { Thread th= rrentThread(); while(a!=0) { try{ intln("wait"+"::"+ tName()); a=0; this.wait(); }catch(Exception e){} } intln("notify"+"::"+ tName()); tify(); } }class B implements Runnable{ a t=new a(); public void run() { t.A(); }}class d{ public static void main(String args[]) { B b=new B(); Thread t=new Thread(b); tName("t"); Thread t2=new Thread(b); tName("t2"); art(); art(); }}這個程序t最后為什么自己有執行了一次notify。
熱心網友
你理解錯了,不是又執行了一次 rify,這個結果是隨機的,運行若干次,結果并不一樣,是因為你兩個線程操作了同一個對象,當其中一個線程wait的時候,另一個線程獲得運行機會,就會執行notify,雖然你的Thread對象是兩個,但是B對象是同一個,也就是說a對象也是同一個。這是可以理解的,下面是我執行你的程序出現的幾個結果://1111111111111 t2線程先獲得運行的結果 ----------Run Java App ----------wait::t2notify::tnotify::t2輸出完成 (耗時 0 秒) - 正常終止// 2222 t線程先獲得運行的結果 ----------Run Java App ----------wait::tnotify::t2notify::t