java多線程wait notify join

來源:互聯網
上載者:User

標籤:join   except   無法   執行   拋出異常   返回   ted   blog   sys   

wait notify 

幾個注意點:

wait 與 notify/notifyAll 方法必須在同步代碼塊中使用,即要先對調用對象加鎖。

當線程執行wait()時,會把當前的鎖釋放,然後讓出CPU,進入等待狀態。

當執行notify/notifyAll方法時,會喚醒一個處於等待該 對象鎖 的線程,然後繼續往下執行,直到執行完退出對象鎖鎖住的地區(synchronized修飾的代碼塊)後再釋放鎖。

從這裡可以看出,notify/notifyAll()執行後,並不立即釋放鎖,而是要等到執行完臨界區中代碼後,再釋放。故,在實際編程中,我們應該盡量線上程調用notify/notifyAll()後,立即退出臨界區。即不要在notify/notifyAll()後面再寫一些耗時的代碼

範例程式碼:

public class Service {    public void testMethod(Object lock) {        try {            synchronized (lock) {                System.out.println("begin wait() ThreadName="                        + Thread.currentThread().getName());                lock.wait();                System.out.println("  end wait() ThreadName="                        + Thread.currentThread().getName());            }        } catch (InterruptedException e) {            e.printStackTrace();        }    }    public void synNotifyMethod(Object lock) {        try {            synchronized (lock) {                System.out.println("begin notify() ThreadName="                        + Thread.currentThread().getName() + " time="                        + System.currentTimeMillis());                lock.notify();                Thread.sleep(5000);                System.out.println("  end notify() ThreadName="                        + Thread.currentThread().getName() + " time="                        + System.currentTimeMillis());            }        } catch (InterruptedException e) {            e.printStackTrace();        }    }}

  

在第3行的testMethod()中調用 wait(),在第17行的synNotifyMethod()中調用notify()

從上面的代碼可以看出,wait() 與  notify/notifyAll()都是放在同步代碼塊中才能夠執行的。如果在執行wait() 與  notify/notifyAll() 之前沒有獲得相應的對象鎖,就會拋出:java.lang.IllegalMonitorStateException異常。

在第8行,當ThreadA線程執行lock.wait();這條語句時,釋放獲得的對象鎖lock,並放棄CPU,進入等待隊列。

當另一個線程執行第23行lock.notify();,會喚醒ThreadA,但是此時它並不立即釋放鎖,接下來它睡眠了5秒鐘(sleep()是不釋放鎖的,事實上sleep()也可以不在同步代碼塊中調用),直到第28行,退出synchronized修飾的臨界區時,才會把鎖釋放。這時,ThreadA就有機會獲得另一個線程釋放的鎖,並從等待的地方起(第24行)起開始執行。

notify 通知的順序不能錯

假設線上程A中執行wait(),線上程B中執行notify()。但如果線程B先執行了notify()然後結束了,線程A才去執行wait(),那此時,線程A將無法被正常喚醒了(還可以通過interrupt()方法以拋出異常的方式喚醒^~^)。

 

join

thread.Join把指定的線程加入到當前線程,可以將兩個交替執行的線程合并為順序執行的線程。比如線上程B中調用了線程A的Join()方法,直到線程A執行完畢後,才會繼續執行線程B。

如果一個線程A執行了thread.join()語句,含義是:當前線程A等待thread線程終止之後也從thread.join()返回 

thread.join還可以指定逾時時間

java多線程wait notify join

聯繫我們

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