Java -- sleep and wait

來源:互聯網
上載者:User

標籤:

 1、二者的來源

  sleep(),是Thread下面的靜態方法/靜態本地方法。

  wait(),是Object()的final方法。

 2、源碼分析

  a、sleep()

 1  public static void sleep(long millis, int nanos) 2     throws InterruptedException { 3         if (millis < 0) { 4             throw new IllegalArgumentException("timeout value is negative"); 5         } 6  7         if (nanos < 0 || nanos > 999999) { 8             throw new IllegalArgumentException( 9                                 "nanosecond timeout value out of range");10         }
12 if (nanos >= 500000 || (nanos != 0 && millis == 0)) {13 millis++;14 }15 16 sleep(millis);17 }

    當調用sleep(millis,nanos)的時候,內部調用的sleep(mills),如下:

public static native void sleep(long millis) throws InterruptedException;

  這是一個靜態本地方法

  由一句話比較重要::: The thread does not lose ownership of any monitors.調用該方法的線程不會失去任何的監控。 不會失去該線程原來擁有的所有鎖。

  執行個體:

  一個實體類User

 1 public class User { 2     private int age; 3  4     public int getAge() { 5         return age; 6     } 7  8     @Override 9     public String toString() {10         return "User [age=" + age + "]";11     }12 13     public void setAge(int age) {14         this.age = age;15     }16 17 }

 

  對該實體類的操作

 1 public class Main { 2  3     public static void main(String[] args) { 4  5         final User user = new User(); 6         user.setAge(10); 7  8         synchronized (user) { 9             try {10                 System.out.println("當前線程  <---->"11                         + Thread.currentThread().getName() + "<-----> 準備休眠");12 13                 Thread.sleep(10000);// 當前線程休眠14 15                 System.out.println("當前線程  <---->"16                         + Thread.currentThread().getName() + "<----->  完成休眠");17 18                 // 建立新的線程,對當前持鎖對象執行相關操作19                 new Thread("new thread") {20                     public void run() {21                         System.out.println("當前線程  --->"22                                 + Thread.currentThread().getName());23                         System.out.println(user.getAge());24                     };25                 }.start();26 27             } catch (InterruptedException e) {28                 // TODO Auto-generated catch block29                 e.printStackTrace();30             }31         }32     }33 }

  執行結果:

當前線程  <---->main<-----> 準備休眠當前線程  <---->main<----->  完成休眠當前線程  ---> new thread10

  所以當在一個synchronized方法中調用sleep()時,線程雖然休眠了,但是對象的機鎖沒有被釋放,其他線程仍然無法訪問這個對象。而wait()方法則會線上程休眠的同時釋放掉機鎖,其他線程可以訪問該對象。所以只有在synchronized 塊結束的時候,線程才會釋放相應的鎖。

 

  b、wait()

The current thread must own this object‘s monitor. The thread releases ownership of this monitor and waits 
until another thread notifies threads waiting on this object‘s monitor to wake up

  調用該方法的線程必須要擁有對象的控制權。調用之後,就會釋放控制權,直到被其他的線程喚醒(notify() | notifyAll()) 。

The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

   之後,被喚醒的線程就繼續等待,直到 重新擷取對象的控制權。

1   public final void wait() throws InterruptedException {2         wait(0);3     }

  調用wait(0)方法--final native

  public final native void wait(long timeout) throws InterruptedException;

  The specified amount of real time has elapsed, more or less.  If timeout is zero, however, then real time is not taken into consideration and the thread simply waits until notified.Then removed from the wait set for this object and re-enabled for thread scheduling. 到達wait時間或者被喚醒(還有一種被喚醒的方式--spurious wakeup,詳細可以查看相關API),就會從線程的wait set中移除,等待重新被調度。

    

                      歡迎拍磚

Java -- sleep and wait

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.