本帖最后由 feigecal 于 2012-6-30 16:05 编辑
class Resource
{
private String name;
private int count=1;
private boolean flag=false;
public synchronized void setName(String name)
{
while(flag)
{
try{this.wait();}catch(Exception e){}
this.name=name+"----"+count++;
System.out.println(Thread.currentThread().getName()+"---shengchan---"+this.name);
flag=true;
this.notifyAll();
}
}
public synchronized void out()
{
while(!flag)
try{this.wait();}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"---xiaofei---"+this.name);
flag=false;
this.notifyAll();
}
}
class Producer implements Runnable
{
private Resource rec;
Producer(Resource rec)
{
this.rec=rec;
}
public void run()
{
while(true)
{
rec.setName("shangpin");
}
}
}
class Consume implements Runnable
{
private Resource rec;
Consume(Resource rec)
{
this.rec=rec;
}
public void run()
{
while(true)
{
rec.out();
}
}
}
class ShopDemo
{
public static void main(String[] args)
{
Resource r=new Resource();
//System.out.println("Hello World!");
Producer p=new Producer(r);
Consume c=new Consume(r);
Thread t1=new Thread(p);
Thread t2=new Thread(p);
Thread t3=new Thread(c);
Thread t4=new Thread(c);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
|
|