sleep()與wait()的差別(java筆記-多線程)

來源:互聯網
上載者:User

標籤:ide   線程   object   tac   main   blog   err   喚醒   對象   

 1 package test; 2  3 public class test1 { 4  5     public static void main(String[] args) { 6  7         new Thread(new thread1()).start(); 8         try { 9             Thread.sleep(5000);10         } catch (InterruptedException e) {11 12             e.printStackTrace();13         }14         new Thread(new thread2()).start();15 16     }17 }18 19 class thread1 implements Runnable {20 21     @Override22     public void run() {23 24         synchronized (test1.class) {25             System.out.println("here is thread1");26             System.out.println("thread1 is waiting");27 28             try {29                 test1.class.wait();// 調用wait,會釋放線程鎖,進入等待鎖定池,直到調用notify方法喚醒,再次進入對象鎖定池準備擷取對象鎖進入運行狀態。30 31             } catch (InterruptedException e) {32 33                 e.printStackTrace();34             }35             System.out.println("thread1 is going");36             System.out.println("thread1 is over");37         }38     }39 }40 41 class thread2 implements Runnable {42 43     @Override44     public void run() {45         //46         synchronized (test1.class) {47             System.out.println("here is thread2");48             System.out.println("thread2 is sleeping");49             test1.class.notify();50             try {51                 Thread.sleep(4000);// 調用sleep,會等待相應時間,等待時線程鎖不釋放,時間到了會進入運行狀態;52                 System.out.println("thread2 is going");53                 System.out.println("thread2 is over");54             } catch (InterruptedException e) {55                 e.printStackTrace();56             }57         }58     }59 }

運行結果:

here is thread1thread1 is waitinghere is thread2thread2 is sleepingthread2 is goingthread2 is overthread1 is goingthread1 is over

注釋掉49行的“test1.class.notify();”

程式會一直處於掛起狀態:

 

here is thread1thread1 is waitinghere is thread2thread2 is sleepingthread2 is goingthread2 is over

 

sleep()方法屬於Thread類;wait()方法屬於Object類。

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

感謝大神 Hongten;

 

sleep()與wait()的差別(java筆記-多線程)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.