JAVA中的wait和notify

來源:互聯網
上載者:User

標籤:static   err   catch   syn   not   進入   led   tno   color   

 1 package com.runnabledemo; 2  3 public class waitnotifydemo01 { 4     public static void main(String[]args)throws Exception { 5         final Object obj = new Object(); 6         Thread t1 = new Thread() { 7             public void run() { 8                 synchronized (obj) { 9                     try {10                         obj.wait();11                         System.out.println("Thread 1 wake up.");12                     } catch (InterruptedException e) {13                     }14                 }15             }16         };17         t1.start();18         Thread.sleep(1000);//We assume thread 1 must start up within 1 sec.19         Thread t2 = new Thread() {20             public void run() {21                 synchronized (obj) {22                     obj.notifyAll();23                     System.out.println("Thread 2 sent notify.");24                 }25             }26         };27         t2.start();28     }29 }

輸出結果為:

Thread 2 sent notify.
Thread 1 wake up.

 

分析:t1 啟動後執行 obj.wait() 時,進入阻塞狀態,讓出時間片並釋放鎖,等待其他線程的喚醒。然後 t2 擷取到 obj,並喚醒 t1,待 t2 執行完畢,釋放鎖後,t1 再繼續執行。

notify()就是對對象鎖的喚醒操作。但有一點需要注意的是notify()調用後,並不是馬上就釋放對象鎖的,而是在相應的synchronized(){}語句塊執行結束,自動釋放鎖後,JVM會在wait()對象鎖的線程中隨機選取一線程,賦予其對象鎖,喚醒線程,繼續執行。這樣就提供了線上程間同步、喚醒的操作。

JAVA中的wait和notify

聯繫我們

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