簡體   English   中英

通知和等待在Java中是什么意思?

[英]what does notify and wait mean in java?

我有正在學習的有關Thread代碼。 我在下面的代碼中不了解它的工作方式。 我的代碼正在處理交通信號燈。 您可以在下面的代碼中解釋嗎?

public void run(){
    while(!stop){
        try{
            switch(lc){
                case GREEN:
                    Thread.sleep(1000);break;//pause for ten second;
                case RED: 
                    Thread.sleep(2000);break;
                case YELLOW:
                    Thread.sleep(1000);break;
            }
        }
        catch(Exception exc){}
         colorChange(); 
    }

}
synchronized void colorChange(){
    switch(lc){
        case GREEN:
            lc=LightColor.YELLOW;break;
        case YELLOW:
            lc=LightColor.RED;break;
        case RED:
            lc=LightColor.GREEN;break;
    }
    changed=true;
    notify();
}
synchronized void waitChange(){
    while(!changed)
         try {
             wait();
             changed=false;
        } catch (InterruptedException ex) {
            Logger.getLogger(ControlLight.class.getName()).log(Level.SEVERE,null, ex);
        }

}

簡要說明如下:

 - wait() tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ).
 - notify() wakes up the first thread that called wait() on the same object.

有關線程的詳細信息,請參閱: http : //docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait%28%29

希望有幫助!

wait():告訴調用線程放棄監視器並進入睡眠狀態,直到其他線程進入同一監視器並調用notify()。

notify():喚醒同一對象上調用wait()的第一個線程。

wait-notify模式用於多種情況,其中一個線程需要告訴其他線程某些事件已經發生。 這些方法旨在提供一種機制,允許線程阻塞直到滿足特定條件為止。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM