java中的sleep()和wait()的區別

原帖:http://www.cnblogs.com/hongten/p/hongten_java_sleep_wait.html

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

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

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

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

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

什麼意思呢?

舉個列子說明:

複製代碼
 1 /**
 2  * 
 3  */
 4 package com.b510.test;
 5 
 6 /**
 7  * java中的sleep()和wait()的區別
 8  * @author Hongten
 9  * @date 2013-12-10
10  */
11 public class TestD {
12 
13     public static void main(String[] args) {
14         new Thread(new Thread1()).start();
15         try {
16             Thread.sleep(5000);
17         } catch (Exception e) {
18             e.printStackTrace();
19         }
20         new Thread(new Thread2()).start();
21     }
22     
23     private static class Thread1 implements Runnable{
24         @Override
25         public void run(){
26             synchronized (TestD.class) {
27             System.out.println("enter thread1...");    
28             System.out.println("thread1 is waiting...");
29             try {
30                 //調用wait()方法,線程會放棄對象鎖,進入等待此對象的等待鎖定池
31                 TestD.class.wait();
32             } catch (Exception e) {
33                 e.printStackTrace();
34             }
35             System.out.println("thread1 is going on ....");
36             System.out.println("thread1 is over!!!");
37             }
38         }
39     }
40     
41     private static class Thread2 implements Runnable{
42         @Override
43         public void run(){
44             synchronized (TestD.class) {
45                 System.out.println("enter thread2....");
46                 System.out.println("thread2 is sleep....");
47                 //只有針對此對象調用notify()方法後本線程才進入對象鎖定池準備獲取對象鎖進入運行狀態。
48                 TestD.class.notify();
49                 //==================
50                 //區別
51                 //如果我們把代碼:TestD.class.notify();給註釋掉,即TestD.class調用了wait()方法,但是沒有調用notify()
52                 //方法,則線程永遠處於掛起狀態。
53                 try {
54                     //sleep()方法導致了程序暫停執行指定的時間,讓出cpu該其他線程,
55                     //但是他的監控狀態依然保持者,當指定的時間到了又會自動恢復運行狀態。
56                     //在調用sleep()方法的過程中,線程不會釋放對象鎖。
57                     Thread.sleep(5000);
58                 } catch (Exception e) {
59                     e.printStackTrace();
60                 }
61                 System.out.println("thread2 is going on....");
62                 System.out.println("thread2 is over!!!");
63             }
64         }
65     }
66 }
複製代碼

運行效果:

複製代碼
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();

運行效果:

複製代碼
enter thread1...
thread1 is waiting...
enter thread2....
thread2 is sleep....
thread2 is going on....
thread2 is over!!!
複製代碼

且程序一直處於掛起狀態。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章