本帖最后由 panjone 于 2011-12-15 23:12 编辑
class Goods
{
Goods()
{
}
private String name;
private static int no=1;
public boolean flag=false;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name=name;
}
public void setGoods(String name)
{
this.name=name;
no++;
}
public void outGoods()
{
System.out.println(no+"---------"+name+"------"+Thread.currentThread().getName());
}
}
class Runsetgoods implements Runnable
{
Runsetgoods(Goods g)
{
this.g=g;
}
private Goods g;
public void run()
{
if(g.flag==false)
{
while(true)
{
while(g.getName()!=null)
try{
this.wait();
}catch(Exception e)
{
}
synchronized(g)
{
if(g.getName()==null)
g.setGoods("香蕉");
g.flag=true;
notifyAll();
}
}
}
if(g.flag=true)
{
while(true)
{
while(g.getName()!=null)
try{
this.wait();
}catch(Exception e)
{
}
synchronized(g)
{
if(g.getName()==null)
g.setGoods("苹果");
g.flag=false;
notifyAll();
}
}
}
}
}
class Runoutgoods implements Runnable
{
private Goods g;
Runoutgoods(Goods g)
{
this.g=g;
}
public void run()
{
while(true)
{
if(g.getName()==null)
try{
this.wait();
}catch(Exception e){}
synchronized(g)
{
if(g.getName()!=null)
g.outGoods();
g.setName(null);
notifyAll();
}
}
}
}
class Product
{
public static void main(String[] args)
{
Goods g=new Goods();
Runsetgoods rs=new Runsetgoods(g);
Runoutgoods ro=new Runoutgoods(g);
Thread t1=new Thread(rs);
Thread t2=new Thread(rs);
Thread t3=new Thread(ro);
t1.start();
t2.start();
t3.start();
}
}
|