日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > java >内容正文

java

Java wait notify

發(fā)布時(shí)間:2023/12/4 java 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java wait notify 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>

Java wait && notify

?wait、notify和notifyAll方法是Object類的final native方法,所以這些方法不能被子類重寫。

方法 notifyAll()

Wakes up all threads that are waiting on this object's monitor.?A?thread waits on an object's monitor by calling one of the{wait} methods.

該方法只能在同步方法或同步塊內(nèi)部調(diào)用。如果當(dāng)前線程不是鎖的持有者,該方法拋出一個(gè)IllegalMonitorStateException異常。

?

方法 notify()

Wakes up a single thread that is waiting on this object's?monitor. If any threads are waiting on this object, one of them?is chosen to be awakened. The choice is arbitrary and occurs at?the discretion of the implementation. A thread waits on an object's?monitor by calling one of the {wait} methods.

該方法只能在同步方法或同步塊內(nèi)部調(diào)用。如果當(dāng)前線程不是鎖的持有者,該方法拋出一個(gè)IllegalMonitorStateException異常。

?

方法 wait()

Causes the current thread to wait until another thread invokes the?{java.lang.Object#notify()} method or the?{java.lang.Object#notifyAll()} method for this object.The current thread must own this object's monitor.?

調(diào)用該方法的線程進(jìn)入WAITING 狀態(tài),只有等待另外線程的通知或被中斷才會(huì)返回,需要注意的是調(diào)用wait方法后,才會(huì)釋放對(duì)象的鎖。

該方法只能在同步方法中調(diào)用。如果當(dāng)前線程不是鎖的持有者,該方法拋出一個(gè)IllegalMonitorStateException異常。下面是一個(gè)wait的示例

synchronized?(object)?{while?(<condition?does?not?hold>)object.wait();// ...? }

?

方法 wait(long millis)&&wait(long millis,int nanos)

Causes the current thread to wait until another thread invokes the?{?java.lang.Object#notify()} method or the?{java.lang.Object#notifyAll()} method for this object, or?some other thread interrupts the current thread, or a certain?amount of real time has elapsed(消逝,過去).

超時(shí)等待一段時(shí)間后,這里的參數(shù)時(shí)間是毫秒,也就是等待長(zhǎng)達(dá)n毫秒,如果沒有通知就超時(shí)返回。

這些方法只能在同步方法中調(diào)用。如果當(dāng)前線程不是鎖的持有者,該方法拋出一個(gè)IllegalMonitorStateException異常。

timeout -- 最大的等待時(shí)間(以毫秒為單位)。

nanos?? -- 額外的時(shí)間,在納秒范圍為0-999999。

?Object.wait()和Object.notify()和Object.notifyAll()必須寫在synchronized方法內(nèi)部或者synchronized塊內(nèi)部,這是因?yàn)?#xff1a;這幾個(gè)方法要求當(dāng)前正在運(yùn)行object.wait()方法的線程擁有object的對(duì)象鎖(內(nèi)置鎖)。即使你確實(shí)知道當(dāng)前上下文線程確實(shí)擁有了對(duì)象鎖,也不能將object.wait()這樣的語句寫在當(dāng)前上下文中。?

?

下面這段代碼的寫法是錯(cuò)誤的。

package?sync;class?A?{public?synchronized?void?printThreadInfo()?throws?InterruptedException?{Thread?t?=?Thread.currentThread();System.out.println("ThreadID:"?+?t.getId()?+?",?ThreadName:"?+?t.getName());} }public?class?ObjectWaitTest?{public?static?void?main(String?args[])?{A?a?=?new?A();//因?yàn)閜rintThreadInfo()方法拋出InterruptedException異常,所以這里必須使用try-catch塊try?{a.printThreadInfo();a.wait();}?catch?(InterruptedException?e)?{//?TODO?Auto-generated?catch?blocke.printStackTrace();}} }

應(yīng)該要這么寫:

package?sync;class?A?{public?synchronized?void?printThreadInfo()?throws?InterruptedException?{Thread?t?=?Thread.currentThread();System.out.println("ThreadID:"?+?t.getId()?+?",?ThreadName:"?+?t.getName());//?this.wait();//一直等待this.wait(1000);//等待1000ms//?super.wait(1000);} }public?class?ObjectWaitTest?{public?static?void?main(String?args[])?{A?a?=?new?A();//因?yàn)閜rintThreadInfo()方法拋出InterruptedException異常,所以這里必須使用try-catch塊try?{a.printThreadInfo();}?catch?(InterruptedException?e)?{//?TODO?Auto-generated?catch?blocke.printStackTrace();}Thread?t?=?Thread.currentThread();System.out.println("ThreadID:"?+?t.getId()?+?",?ThreadName:"?+?t.getName());} }

完整示例,

import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.TimeUnit;public class WaitNotifyDemo {static boolean flag = true;static Object lock = new Object();public static void main(String[] args) throws InterruptedException {Thread waitThread = new Thread(new Wait(), "waitThread");waitThread.start();TimeUnit.SECONDS.sleep(1);Thread notifyThread = new Thread(new Notify(), "notifyThread");notifyThread.start();}static class Wait implements Runnable {@Overridepublic void run() {// 加鎖 擁有l(wèi)ock 的 monitorsynchronized (lock) {while (flag) {try {System.out.println(Thread.currentThread() + " flag is true. wait @ " +new SimpleDateFormat("HH:mm:ss").format(new Date()));// 釋放了對(duì)象的監(jiān)視器鎖lock.wait();} catch (InterruptedException e) {e.printStackTrace();}}System.out.println(Thread.currentThread() + " flag is false. running @ " +new SimpleDateFormat("HH:mm:ss").format(new Date()));}}}static class Notify implements Runnable {@Overridepublic void run() {synchronized (lock) {System.out.println(Thread.currentThread() + " hold lock. notify @ " +new SimpleDateFormat("HH:mm:ss").format(new Date()));lock.notifyAll();flag = false;try {Thread.sleep(1000 * 5);} catch (InterruptedException e) {e.printStackTrace();}}}} }

以上就是關(guān)于wait和notify方法的用法。

參考:http://www.cnblogs.com/xwdreamer/archive/2012/05/12/2496843.html

后記:Thread.sleep()與Object.wait()二者都可以暫停當(dāng)前線程,釋放CPU控制權(quán),主要的區(qū)別在于Object.wait()在釋放CPU同時(shí),釋放了對(duì)象鎖的控制。

==============END==============

轉(zhuǎn)載于:https://my.oschina.net/xinxingegeya/blog/345816

總結(jié)

以上是生活随笔為你收集整理的Java wait notify的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。