wait()
和notify()
来了解在访问共享资源或依赖它们的状态时实现线程的必要性。我看到的想法是监视对象并等待其可用性,在使用后释放它们,以使它们对其他线程/方法可用,但为什么需要这些方法,而不是将相关对象声明为静态易失性,以便其他线程在不调用这些方法的情况下了解状态的变化?
例如,在餐厅里有两位厨师。其中一位是好厨师(更好的烹饪质量...),携带布尔值
isGoodCook = true
,而第二位厨师是坏厨师,携带布尔值isGoodCook = false
。同时只有一个厨师可以使用设备进行烹饪。坏厨师烹饪一段特定时间(= cookingTime),而好厨师偶尔进入厨房接管坏厨师的烹饪任务。好厨师在烹饪过程中永远不能被打断,并且一旦开始就会一直烹饪整个cookingTime。
(当好厨师接替烹饪餐点的部分时,坏厨师停止烹饪。)
好厨师停止烹饪餐点后,坏厨师必须重新开始准备餐点的任务。
private boolean cooking; //is equipment used at the moment
private boolean isGoodCook;
private boolean cookingDesire; //indicating to chef to stop cooking
private int cookingTime;
public CookingTask(boolean isGoodCook, int cookingTime)
{
this.isGoodCook = isGoodCook;
this.cookingTime = cookingTime;
}
public void run()
{
if(isGoodCook)
{
//notify actual cook to stop cooking
cookingDesire = true;
}
//wait til equipment to cook
//is available
while(cooking)
{
try
{
wait();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
//reserve equipment
cooking = true;
cookingDesire = false;
//notify other threads (= bad cook)
notifyAll();
startCooking();
}
private void startCooking()
{
for(int i = 0; i < cookingTime; cookingTime--)
{
try
{
Thread.sleep(1000);
//if good chef comes in
if(cookingDesire)
{
//bad chef starts to pause
startBreak();
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
cooking = false;
}
public void startBreak()
{
//bad chef stops cooking
cooking = false;
notifyAll();
//measure break time of bad chef
long stopCookingTime = System.currentTimeMillis();
while(cookingTime > 0 && cooking)
{
try
{
wait();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
int pausedTime = toIntExact((System.currentTimeMillis() - stopCookingTime)/1000);
//calculate remaining cookingTime
cookingTime -= pausedTime;
cooking = true;
notifyAll();
}
也许有人有时间阅读并简要概述我对多线程监控/
wait()
和notify()
的误解,我将不胜感激!