class Res
{
private String name;
private boolean flag;
private int count = 0;
public synchronized void set(String name)throws InterruptedException
{
while(flag)
wait();
this.name = name;
add();
System.out.println(Thread.currentThread().getName()+"----生产----"+name+"::"+count);
flag = true;
notifyAll();
}
public synchronized void out()throws InterruptedException
{
while(!flag)
wait();
System.out.println(Thread.currentThread().getName()+"....消费...."+name+"::"+count);
flag = false;
notifyAll();
}
public void add()
{
count++;
}
}
class Input implements Runnable
{
private Res r;
Input(Res r)
{
this.r = r;
}
public void run()
{
while(true)
{
try{r.set("商品");}catch(InterruptedException e){}
}
}
}
class Output implements Runnable
{
private Res r;
Output(Res r)
{
this.r = r;
}
public void run()
{
while(true)
{
try{r.out();}catch(InterruptedException e){}
}
}
}
class ResDemo
{
public static void main(String[] args)
{
Res r = new Res();
//创建两个生成者
new Thread(new Input(r)).start();
new Thread(new Input(r)).start();
//创建两个消费者
new Thread(new Output(r)).start();
new Thread(new Output(r)).start();
}
}