/*
多线程:一个生产者一个消费者
*/
class Resource
{
private String name;
private int age;
boolean flag=false;
public synchronized void setResource(String name,int count) throws InterruptedException
{
while(flag)
//this.wait();
{this.wait();this.notify();System.out.println("生产者while continue");}
this.name=name+count;
System.out.println("生产者"+this.name+"......");
flag=true;
//this.notify();
}
public synchronized String getName()throws InterruptedException
{
while(!flag)
//this.wait();
{this.wait();this.notify();System.out.println("消费者while continue");}
flag=false;
//this.notify();
return this.name;
}
}
class ProducerThread implements Runnable
{
int count=1;
public Resource r=new Resource();
public Resource getResource()
{
return r;
}
public void run()
{
while(true)
{
try{r.setResource("张三",count);}catch(InterruptedException ex){}
count++;
}
}
}
class SellerThread implements Runnable
{
private Resource r;
int count=20;
public SellerThread(Resource r)
{
this.r=r;
}
public void run()
{
while(true)
try{System.out.println("消费者"+r.getName()+"...");}catch(InterruptedException ex){}
}
}
class OneProducerSellerThread
{
public static void main(String[] args) throws InterruptedException
{
ProducerThread pt=new ProducerThread();
//SellerThread st=new SellerThread();
new Thread(pt).start();
new Thread(new SellerThread(pt.getResource())).start();
}
}