重点内容生产者与消费者代码块
package com.carlinfo.thread.prod.prodcon;
/**
* 出菜口
* @author WangshMac
*/
public class Storage
{
/**
* 有几盘菜
*/
private static int size ;
/**
* 厨师放菜
* 如果有菜,就别放了
*/
public synchronized void add()
{
if(this.size > 0 )
{
System.out.println(Thread.currentThread() + "==有菜了==");
try
{
/* 等待;什么时候唤醒,是等待服务员叫醒 */
this.wait();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}else
{
this.size ++ ;
System.out.println(Thread.currentThread() + "==我放了一盘菜==" + this.size);
/* 把所有的服务员叫醒 */
this.notifyAll();
}
}
/**
* 服务员端菜
* 如果木有菜,就别端了
*/
public synchronized void remove()
{
if(this.size > 0 )
{
this.size -- ;
System.out.println(Thread.currentThread() + "==我端了一盘菜==" + this.size);
/* 把所有的厨师叫醒 */
this.notifyAll();
}else
{
System.out.println(Thread.currentThread() + "==木有菜了==");
/* 如果这里面木有菜了,也等待 */
try
{
this.wait();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}