線程中的等待與喚醒

來源:互聯網
上載者:User

標籤:

上一篇文章講到join()方法的時候,用到了一個函數即為yield()方法,它的作用是將cup讓與具有相同優先順序的線程去使用。本篇文章就為大家講述線程中的一些關於等待和喚醒的函數。

sleep():

使當前線程暫停使用一段時間,讓其它線程繼續有機會執行,但是它並不釋放對象鎖,也就是說有synchronized關鍵字的時候,其它線程仍然不能訪問其共用資源。sleep()方法需要使用者去設定阻塞的時間。在使用者佈建sleep()方法的時候,該線程一定是不會被執行的,所以會讓優先順序低的線程有機會去執行。也就是說,如果優先順序高的線程沒有設定sleep()或者沒有I/O阻塞的時候,優先順序低的線程只能出於等待狀態,只有當優先順序較高的線程執行完畢後,它才有機會執行。

yield():

此方法與sleep()方法具有相同的功能,只是該方法的時間並不是由我們自己來設定的,而是由系統完成的,並且它只能讓同優先順序的線程有機會先執行。也就是說,執行yeld()方法,此線程會去尋找有沒有與它優先順序相同的線程,如果有,則讓與它優先順序相同的線程執行。若沒有,則返回繼續執行原來的線程。所以yield()方法只能給同優先順序的線程執行的機會,而不會給低優先順序的線程機會。(不給別人留活路啊)。

具體程式碼範例如下:

package sleepandwait;/** * 調用sleep()方法時,我們可以自己去指定該線程需要休息的時間, * 調用yield()方法時,我們並不知道該線程需要休息多長時間,而且 * yield()方法是讓相同優先順序的線程先執行。 * @author Administrator * */public class Test {public static void main(String[] args) {Thread t1 = new Thread(new MyRunnable(2000));t1.setPriority(9);t1.start();Thread t2 = new Thread(new MyRunnable(3000));t2.setPriority(6);t2.start();Thread t3 = new Thread(new MyRunnable(5000));t3.setPriority(9);t3.start();}}class MyRunnable implements Runnable{private int time;public MyRunnable(int time){this.time = time;}@Overridepublic void run() {try {Thread.sleep(time);} catch (InterruptedException e) {e.printStackTrace();}//Thread.yield();//System.out.println("我是線程:"//+Thread.currentThread().getName()+//"我調用的是yield()方法,我被阻塞了多久我不知道...");System.out.println("我是線程:"+Thread.currentThread().getName()+"我被阻塞 了"+time+"秒!");}}

當我們注釋掉sleep()方法,換成wait()方法時,會看到是t1和t3先執行,最後是t2。

注意:sleep()和yield()都只是暫停當前線程的執行,並不會讓出共用資源。

wait()、notify()、notifyAll():

wait()、notify()、notifyAll()都是用於協調多個線程對共用資料的存取,所以必須在synchronized語句塊中使用。synchronized關鍵字用來保護共用資源,阻止其它線程對共用資源的存取,但是這樣就會使程式很不靈活。如何才能讓當前線程還沒有退出synchronized的時候,能夠讓其它線程進行對共用資源進行訪問呢,這三個方法就會讓你的程式靈活起來

wait()方法使當前線程暫停執行並釋放對象鎖標誌,讓其它線程進入synchronized資料區塊,當前線程被放入對象等待池中,當調用notify()方法後,將會有任意一個線程被移回鎖標誌等待池中。notifyAll()方法將從對象等待池中移走所有等待那個對象的線程並放到鎖標誌等待池中。

notify():喚醒此對象監視器上的單個線程。

notifyAll():喚醒此對象監視器上的所有線程。

wait():讓當前線程處於阻塞狀態,直到其它線程調用此對象的notify()或notifyAll()方法,當前線程被喚醒。

wait(long timeout) :讓當前線程處於阻塞狀態,直到其它線程調用此對象的notify()或notifyAll()方法,或者超出指定的時間等待量,當前線程被喚醒。

notify()測試代碼如下:

package sleepandwait;public class MyThread extends Thread{public MyThread(String name){super(name);}public void run(){synchronized(this){System.out.println(Thread.currentThread().getName()+"等待喚醒...");System.out.println("我是線程"+Thread.currentThread().getName()+":我被call notify!");//喚醒當前線程的wait()等待notify();}}}
package sleepandwait;public class TestNotify {public static void main(String[] args) {MyThread t1 = new MyThread("t1線程");synchronized(t1){try{System.out.println(Thread.currentThread().getName()+" start...");t1.start();System.out.println(Thread.currentThread().getName()+" wait!");//t1線程進入等待狀態t1.wait();System.out.println(Thread.currentThread().getName()+" continue...");}catch(Exception e){e.printStackTrace();}}}}
notifyAll()測試代碼:

package sleepandwait;public class TestnotifyAll {private static Object obj = new Object();public static void main(String[] args) {Thread t1 = new ThreadA("t1");Thread t2 = new ThreadA("t2");Thread t3 = new ThreadA("t3");t1.start();t2.start();t3.start();try {System.out.println(Thread.currentThread().getName()+" sleep3000");Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}synchronized(obj){//主線程等待喚醒System.out.println(Thread.currentThread().getName()+"notifyAll.");obj.notifyAll();}}static class ThreadA extends Thread{public ThreadA(String name){super(name);}public void run(){synchronized(obj){try{System.out.println(Thread.currentThread().getName()+"wait!");//喚醒當前線程的wait等待obj.wait();System.out.println(Thread.currentThread().getName()+" continue!");}catch(InterruptedException e){e.printStackTrace();}}}}}

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

線程中的等待與喚醒

聯繫我們

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