通知和等待在java中是什么意思?
我有我正在学习的通知和等待在java中是什么意思?,java,Java,我有我正在学习的线程。我不明白在下面的代码中它是如何工作的。我的代码正在处理交通信号灯。你能用下面的代码解释吗 public void run(){ while(!stop){ try{ switch(lc){ case GREEN: Thread.sleep(1000);break;//pause for ten second; case RE
线程
。我不明白在下面的代码中它是如何工作的。我的代码正在处理交通信号灯。你能用下面的代码解释吗
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.
有关螺纹的详细信息,请参考:
希望这有帮助 等待():告诉调用线程放弃监视器并进入睡眠状态,直到其他线程进入同一监视器并调用notify()
notify():唤醒在同一对象上调用wait()的第一个线程
wait notify
模式用于一组广泛的情况,其中一个线程需要告诉其他线程发生了某个事件。这些方法旨在提供一种机制,允许线程阻塞,直到满足特定条件。您的代码不是逻辑代码。每个case语句都应该有中断。每个case都有中断。抱歉。我现在知道了。但是这个代码似乎还不完整。run()方法应该有更多的逻辑。您可能还想看看Thread.sleep。你真的没有给你的车你的评论所暗示的那么多时间。