瀏覽量:166次
java wait是怎樣的呢?下面就讓我們一起來了解一下吧:
wait()方法是屬于java中的一個方法,它的作用是能夠讓當(dāng)前線程進入等待狀態(tài),同時,wait()也會讓當(dāng)前線程釋放它所持有的鎖。直到其他線程調(diào)用此對象的notify()方法或者notifyAll()方法,當(dāng)前線程被喚醒(也就是進入“就緒狀態(tài)”)。
說明:
notify()和notifyAll()方法的作用,則是用于喚醒當(dāng)前對象上的等待線程;notify()方法是喚醒單個線程,而notifyAll()是喚醒所有的線程。
參考范例:
?package?com.citi.test.mutiplethread.demo0503;??import?java.util.Date;??public?class?WaitTest?{?????public?static?void?main(String[]?args)?{?????????ThreadA?t1=new?ThreadA("t1");?????????System.out.println("t1:"+t1);?????????synchronized?(t1)?{?????????????try?{?????????????????//啟動線程?????????????????System.out.println(Thread.currentThread().getName()+"?start?t1");?????????????????t1.start();?????????????????//主線程等待t1通過notify喚醒。?????????????????System.out.println(Thread.currentThread().getName()+"?wait()"+?new?Date());?????????????????t1.wait();//?不是使t1線程等待,而是當(dāng)前執(zhí)行wait的線程等待?????????????????System.out.println(Thread.currentThread().getName()+"?continue"+?new?Date());?????????????}?catch?(Exception?e)?{?????????????????e.printStackTrace();?????????????}?????????}?????}?}??class?ThreadA?extends?Thread{?????public?ThreadA(String?name)?{?????????super(name);?????}?????@Override?????public?void?run()?{?????????synchronized?(this)?{?????????????System.out.println("this:"+this);?????????????try?{?????????????????Thread.sleep(2000);//使當(dāng)前線程阻塞1秒?????????????}?catch?(InterruptedException?e)?{?????????????????//?TODO?Auto-generated?catch?block?????????????????e.printStackTrace();?????????????}?????????????System.out.println(Thread.currentThread().getName()+"?call?notify()");?????????????this.notify();?????????}?????}?}
[聲明]本網(wǎng)轉(zhuǎn)載網(wǎng)絡(luò)媒體稿件是為了傳播更多的信息,此類稿件不代表本網(wǎng)觀點,本網(wǎng)不承擔(dān)此類稿件侵權(quán)行為的連帶責(zé)任。故此,如果您發(fā)現(xiàn)本網(wǎng)站的內(nèi)容侵犯了您的版權(quán),請您的相關(guān)內(nèi)容發(fā)至此郵箱【779898168@qq.com】,我們在確認后,會立即刪除,保證您的版權(quán)。
官網(wǎng)優(yōu)化
整站優(yōu)化
渠道代理
400-655-5776