class Resource
{
private String name;
private int num=1;
private boolean flag=false;
public synchronized void set(String name)
{
this.name=(name+"....."+(num++));
if(flag)
try
{
this.wait();
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"........."+"生产者"+"..."+this.name);
this.flag=true;
this.notify();
}
public synchronized void get()
{
if(!flag)
try
{
this.wait();
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"..."+"消费者"+"..."+this.name);
this.flag=false;
this.notify();
}
}
class Producer implements Runnable
{
private Resource r;
Producer(Resource r)
{
this.r=r;
}
public void run()
{
while(true)
{
r.set("商品");
}
}
}
class Consumer implements Runnable
{
private Resource r;
Consumer(Resource r)
{
this.r=r;
}
public void run()
{
while(true)
{
r.get();
}
}
}
class ProducerConsumerTest2
{
public static void main(String[] args)
{
Resource r=new Resource();
Producer pro=new Producer(r);
Consumer con=new Consumer(r);
Thread t1=new Thread(pro);
Thread t2=new Thread(con);
t1.start();
t2.start();
}
}
结果是如下,问题出现在哪里?
file:///C:/Documents%20and%20Settings/Administrator/Application%20Data/Tencent/Users/452953881/QQ/WinTemp/RichOle/)U]X61B@D7]JC9OH%7D%7DAU0AI.jpg
|