03 執行緒的通知notify與等待wait

2022-06-26 18:15:14 字數 2417 閱讀 6377

wait()、notify、notifyall()方法

wait()、notify()、notifyall()是三個定義在object類裡的方法,可以用來控制線程的狀態。

這三個方法最終呼叫的都是jvm級的native方法。隨著jvm執行平台的不同可能有些許差異。

public class notifyalldemo catch (interruptedexception e)}}

});thread threadb = new thread(new runnable() catch (interruptedexception e)}}

});thread threadc = new thread(new runnable()

}});

threada.start();

threadb.start();

thread.sleep(1000);

threadc.start();

threada.join();

threadb.join();

threadc.join();

system.out.println("main over");

//呼叫notify()

//threada get rea lock

//threada begin wait

//threadb get rea lock

//threadb begin wait

//threadc begin notify

//threada end wait

//呼叫notifyall()

//threada get rea lock

//threada begin wait

//threadb get rea lock

//threadb begin wait

//threadc begin notify

//threada end wait

//threadb end wait

//main over

}}

補充
/**

* p56

執行緒t1 執行緒t2

取得object監視器

object.wait()

釋放object監視器

取得object監視器

object.notify()

等待object監視器 釋放object監視器

重獲object監視器

繼續執行

* * t1在正確執行wait()方法前,首先必須獲得object物件的監視器,而wait()方法在執行後,會釋放這個監視器,這樣做的

* 目的是使得其他等待在object物件上的執行緒不至於因為t1的休眠而全部無法正常執行。

* 執行緒t2在notify()呼叫前,必須獲得object的監視器,t1已經釋放了這個監視器,因此,t2可以順利獲得object的監視器。

* 接著,t2執行了notify()方法嘗試喚醒乙個等待執行緒,這裡假設喚醒了t1,t1在被喚醒後,要做的第一件事並不是執行後續的**,

* 而是要嘗試重新獲得object的監視器,而這個監視器也正是t1在wait()方法執行前所持有的那個。如果暫時無法獲得,t1還必須

* 要等待這個監視器,當監視器順利獲得後,t1才可以真正意義上的繼續執行。

*/public class waitandnotifydemo catch (interruptedexception e)

system.out.println(system.currenttimemillis()+":t1 end!");}}

}public static class t2 extends thread catch (interruptedexception e) }}

}public static void main(string args)

}

/**

* 模擬過時的掛起(suspend),繼續執行(resume)

*/public class waitandnotifydemo2

//繼續執行執行緒

public void resumeme()

}@override

public void run() catch (interruptedexception e)

}synchronized (object)

thread.yield();}}

}}

public static class readobjectthread extends thread

thread.yield();}}

}public static void main(string args) throws interruptedexception

}

03 Java多執行緒 執行緒等待通知機制

三 執行緒等待通知 四 參考 如果等待時長為t,當前時間為now,那麼now t以後超時 long overtime now t long remain t while result不滿足 remian 0 return result shop類模擬商店,初始狀態玩具是nothing,執行緒等待玩具...

wait與notify執行緒之間的通訊

1.wait與notify是使用在同步 塊或同步方法中的 2.他們都是object的方法 3.notify是需要獲取鎖的,會隨機喚醒乙個處理等待狀態的執行緒 4.wait方法是會釋放鎖的 5.notifyall會喚醒所有wait的執行緒,但是拿到cup時間片的執行緒只有乙個 6.thread類的乙個...

執行緒通知與等待

當乙個執行緒呼叫乙個共享變數的 wait 方法時,該呼叫執行緒會被阻塞掛起,直到發生下面幾件事情之一才返回。其他執行緒呼叫了該共享物件的 notify 或者 notify 方法 其他執行緒呼叫了該執行緒的 interrupt 方法,該執行緒丟擲 interruptedexception 異常返回。注...