1. 程式人生 > >wait()與sleep()方法的區別

wait()與sleep()方法的區別

相同點:

都使程式進入一個暫停的狀態,

不同點:

wait():當執行緒等待狀態為真,其他程式申請執行緒時,該執行緒會釋放執行緒鎖;如果該執行緒呼叫notify()方法,本執行緒會進入物件鎖定池準備,獲取物件鎖進入執行狀態。

.sleep();程式暫停執行指定的時間,釋放cpu資源,在呼叫sleep()方法的過程中,執行緒不會釋放物件鎖。當指定時間到了,就會自動恢復執行狀態。

測試程式碼

package cn.test;
/**
 * java中的sleep()和wait()的區別
 * @author 陳磊
 *
 */
public class WaitAndSleep {

	    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{
	        public void run(){
	            synchronized (WaitAndSleep.class) {
	            System.out.println("enter thread1...");    
	            System.out.println("thread1 is waiting...");
	            try {
	                //呼叫wait()方法,執行緒會放棄物件鎖,進入等待此物件的等待鎖定池
	            	WaitAndSleep.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{
	        public void run(){
	            synchronized (WaitAndSleep.class) {
	                System.out.println("enter thread2....");
	                System.out.println("thread2 is sleep....");
	                //只有針對此物件呼叫notify()方法後本執行緒才進入物件鎖定池準備獲取物件鎖進入執行狀態。
	                WaitAndSleep.class.notify();
	                //==================
	                //區別
	                //如果我們把程式碼:WaitAndSleep.class.notify();給註釋掉,即WaitAndSleep.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 is waiting...
enter thread2....
thread2 is sleep....
thread2 is going on....
thread2 is over!!!
thread1 is going on ....
thread1 is over!!!

如果註釋掉程式碼:

WaitAndSleep.class.notify();

測試結果:

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