Java中的多執行緒你只要看這一篇就夠了
阿新 • • 發佈:2018-12-18
/**
* 生產者生產出來的產品交給店員
*/
public synchronized void produce()
{
if(this.product >= MAX_PRODUCT)
{
try
{
wait();
System.out.println("產品已滿,請稍候再生產");
}
catch(InterruptedException e)
{
e.printStackTrace();
}
return;
}
this.product++;
System.out.println("生產者生產第" + this.product + "個產品.");
notifyAll(); //通知等待區的消費者可以取出產品了
}
/**
* 消費者從店員取產品
*/
public synchronized void consume()
{
if(this.product <= MIN_PRODUCT)
{
try
{
wait();
System.out.println( "缺貨,稍候再取");
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return;
}
System.out.println("消費者取走了第" + this.product + "個產品.");
this.product--;
notifyAll(); //通知等待去的生產者可以生產產品了
}