欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解Java中的sleep()和wait()的區(qū)別

 更新時(shí)間:2017年09月21日 08:36:58   投稿:lqh  
這篇文章主要介紹了詳解Java中的sleep()和wait()的區(qū)別的相關(guān)資料,希望通過本文能幫助到大家,需要的朋友可以參考下

詳解Java中的sleep()和wait()的區(qū)別

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

sleep()方法導(dǎo)致了程序暫停執(zhí)行指定的時(shí)間,讓出cpu該其他線程,但是他的監(jiān)控狀態(tài)依然保持者,當(dāng)指定的時(shí)間到了又會(huì)自動(dòng)恢復(fù)運(yùn)行狀態(tài)。

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

而當(dāng)調(diào)用wait()方法的時(shí)候,線程會(huì)放棄對象鎖,進(jìn)入等待此對象的等待鎖定池,只有針對此對象調(diào)用notify()方法后本線程才進(jìn)入對象鎖定池準(zhǔn)備

獲取對象鎖進(jìn)入運(yùn)行狀態(tài)。

什么意思呢?

舉個(gè)列子說明:

/**
 * 
 */
package com.b510.test;

/**
 * java中的sleep()和wait()的區(qū)別
 * @author Hongten Java學(xué)習(xí)交流QQ群:589809992 我們一起學(xué)Java!
 * @date 2013-12-10
 */
public class TestD {

  public static void main(String[] args) {
    new Thread(new Thread1()).start();
    try {
      Thread.sleep(5000);
    } catch (Exception e) {
      e.printStackTrace();
    }
    new Thread(new Thread2()).start();
  }

  private static class Thread1 implements Runnable{
    @Override
    public void run(){
      synchronized (TestD.class) {
      System.out.println("enter thread1...");  
      System.out.println("thread1 is waiting...");
      try {
        //調(diào)用wait()方法,線程會(huì)放棄對象鎖,進(jìn)入等待此對象的等待鎖定池
        TestD.class.wait();
      } catch (Exception e) {
        e.printStackTrace();
      }
      System.out.println("thread1 is going on ....");
      System.out.println("thread1 is over!!!");
      }
    }
  }

  private static class Thread2 implements Runnable{
    @Override
    public void run(){
      synchronized (TestD.class) {
        System.out.println("enter thread2....");
        System.out.println("thread2 is sleep....");
        //只有針對此對象調(diào)用notify()方法后本線程才進(jìn)入對象鎖定池準(zhǔn)備獲取對象鎖進(jìn)入運(yùn)行狀態(tài)。
        TestD.class.notify();
        //==================
        //區(qū)別
        //如果我們把代碼:TestD.class.notify();給注釋掉,即TestD.class調(diào)用了wait()方法,但是沒有調(diào)用notify()
        //方法,則線程永遠(yuǎn)處于掛起狀態(tài)。
        try {
          //sleep()方法導(dǎo)致了程序暫停執(zhí)行指定的時(shí)間,讓出cpu該其他線程,
          //但是他的監(jiān)控狀態(tài)依然保持者,當(dāng)指定的時(shí)間到了又會(huì)自動(dòng)恢復(fù)運(yùn)行狀態(tài)。
          //在調(diào)用sleep()方法的過程中,線程不會(huì)釋放對象鎖。
          Thread.sleep(5000);
        } catch (Exception e) {
          e.printStackTrace();
        }
        System.out.println("thread2 is going on....");
        System.out.println("thread2 is over!!!");
      }
    }
  }
}

運(yùn)行效果:

enter thread1...
thread1 is waiting...
enter thread2....
thread2 is sleep....
thread2 is going on....
thread2 is over!!!
thread1 is going on ....
thread1 is over!!!

如果注釋掉代碼:

1 TestD.class.notify();

運(yùn)行效果:

enter thread1...
thread1 is waiting...
enter thread2....
thread2 is sleep....
thread2 is going on....
thread2 is over!!!

且程序一直處于掛起狀態(tài)。

如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

相關(guān)文章

最新評論