衡阳派盒市场营销有限公司

您好,歡迎來電子發燒友網! ,新用戶?[免費注冊]

您的位置:電子發燒友網>源碼下載>java源碼下載>

分析在java中sleep和wait的不同

大小:1.5 MB 人氣: 2017-09-27 需要積分:2

  對于sleep()方法,我們首先要知道該方法是屬于Thread類中的。而wait()方法,則是屬于Object類中的。

  sleep()方法導致了程序暫停執行指定的時間,讓出cpu該其他線程,但是他的監控狀態依然保持者,當指定的時間到了又會自動恢復運行狀態。

  在調用sleep()方法的過程中,線程不會釋放對象鎖。

  而當調用wait()方法的時候,線程會放棄對象鎖,進入等待此對象的等待鎖定池,只有針對此對象調用notify()方法后本線程才進入對象鎖定池準備

  獲取對象鎖進入運行狀態。

  什么意思呢?

  舉個列子說明:

  /** * */packagecom.b510.test; /** * java中的sleep()和wait()的區別 *@authorHongten Java學習交流QQ群:589809992 我們一起學Java! *@date2013-12-10 */publicclassTestD{publicstaticvoidmain(String[] args) { newThread( newThread1()).start();try{ Thread.sleep( 5000); } catch(Exception e) { e.printStackTrace(); } newThread(newThread2()).start(); }privatestaticclassThread1implementsRunnable{@Overridepublicvoidrun(){synchronized(TestD.class) { System.out.println( “enter thread1.。。”); System.out.println(“thread1 is waiting.。。”); try{ //調用wait()方法,線程會放棄對象鎖,進入等待此對象的等待鎖定池TestD.class.wait(); } catch(Exception e) { e.printStackTrace(); } System.out.println(“thread1 is going on 。。.。”); System.out.println( “thread1 is over!!!”); } } }privatestaticclassThread2implementsRunnable{@Overridepublicvoidrun(){synchronized(TestD.class) { System.out.println( “enter thread2.。。.”); System.out.println(“thread2 is sleep.。。.”); //只有針對此對象調用notify()方法后本線程才進入對象鎖定池準備獲取對象鎖進入運行狀態。TestD.class.notify(); //==================//區別//如果我們把代碼:TestD.class.notify();給注釋掉,即TestD.class調用了wait()方法,但是沒有調用notify()//方法,則線程永遠處于掛起狀態。try{ //sleep()方法導致了程序暫停執行指定的時間,讓出cpu該其他線程,//但是他的監控狀態依然保持者,當指定的時間到了又會自動恢復運行狀態。//在調用sleep()方法的過程中,線程不會釋放對象鎖。Thread.sleep( 5000); }catch(Exception e) { e.printStackTrace(); } System.out.println( “thread2 is going on.。。.”); System.out.println( “thread2 is over!!!”); } } } }

  運行效果:

  enter thread1.。。 thread1 iswaiting.。。 enter thread2.。。. thread2 issleep.。。. thread2 isgoingon.。。. thread2 isover!!! thread1 isgoing on.。。. thread1 isover!!!

  如果注釋掉代碼:

  1TestD .class.notify() ;

  運行效果:

  enter thread1.。。 thread1 iswaiting.。。 enter thread2.。。. thread2 issleep.。。. thread2 isgoingon.。。. thread2 isover!!!

  且程序一直處于掛起狀態。返回

非常好我支持^.^

(0) 0%

不好我反對

(0) 0%

      發表評論

      用戶評論
      評價:好評中評差評

      發表評論,獲取積分! 請遵守相關規定!

      ?
      路劲太阳城怎么样| 百家乐官网博之道娱乐城| 百家乐注码法| 现金百家乐官网网上娱乐| 百家乐投注网站是多少| 百家乐官网网站那个好| 御匾会百家乐娱乐城| 真人百家乐官网策略| 百家乐桌布无纺布| 广州百家乐官网酒店用品制造有限公司| 百家乐官网破战| 通化大嘴棋牌官方下载| 百家乐真人视屏游戏| 百家乐官网游戏玩法规则| 疯狂百家乐游戏| 自贡百家乐官网娱乐场开户注册| 瑞丰国际娱乐场| 单机百家乐在线小游戏| 游戏机百家乐官网的技术| 澳门顶级赌场娱乐城| 百家乐桌颜色可定制| 澳门百家乐官网破解方法| 真人娱乐城送体验金18| 百家乐现金网信誉排名| 百家乐官网游戏网上投注| 海立方百利宫娱乐城| 华盛顿百家乐的玩法技巧和规则| 24山向方位度数| 永利高百家乐官网开户| 大发888手机客户端| 百家乐赌缆十三式| 百家乐官网槛| 足球投注现金网| 百家乐免费改| 百家乐赢的秘诀| 南宁百家乐官网赌机| tt线上娱乐| 威尼斯人娱乐场下载| 威尼斯人娱乐场内幕| 澳门百家乐海星王娱乐城| 百家乐官网是怎样算牌|