這篇文章主要介紹了詳解Java中的sleep()和wait()的區別的相關資料,希望透過本文能幫助到大家,需要的朋友可以參考下
詳解Java中的sleep()和wait()的區別
對於sleep()方法,我們首先要知道該方法是屬於Thread類別中的。而wait()方法,則是屬於Object類別中的。
sleep()方法導致了程式暫停執行指定的時間,讓出cpu該其他線程,但是他的監控狀態依然保持者,當指定的時間到了又會自動恢復運行狀態。
在呼叫sleep()方法的過程中,執行緒不會釋放物件鎖定。
而當呼叫wait()方法的時候,執行緒會放棄物件鎖,進入等待此物件的等待鎖定池,只有針對此物件呼叫notify()方法後本執行緒才進入物件鎖定池準備
取得物件鎖定進入運作狀態。
什麼意思呢?
舉個列子說明:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
package com.b510.test;
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 {
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...." );
TestD. class .notify();
try {
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println( "thread2 is going on...." );
System.out.println( "thread2 is over!!!" );
}
}
}
}
|
登入後複製
執行效果:
1 2 3 4 5 6 7 8 | 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 2 3 4 5 6 | enter thread1...
thread1 is waiting...
enter thread2....
thread2 is sleep....
thread2 is going on....
thread2 is over!!!
|
登入後複製
且程式一直處於掛起狀態。
以上是Java中關於sleep()與wait()的差異詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!