多线程(多个生产者多个消费者)


/*
多线程:一个生产者一个消费者
*/

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.name=name+count;
System.out.println(Thread.currentThread().getName()+"生产者"+this.name+"......");
flag=true;
//this.notify();
this.notifyAll();
}
public synchronized String getName()throws InterruptedException
{
while(!flag)
this.wait();
flag=false;
//this.notify();
this.notifyAll();
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(Thread.currentThread().getName()+"消费者"+r.getName()+"...");}catch(InterruptedException ex){}
}
}
class ManyProducerSellerThread
{
public static void main(String[] args) throws InterruptedException
{
ProducerThread pt=new ProducerThread();
new Thread(pt).start();
new Thread(pt).start();
new Thread(new SellerThread(pt.getResource())).start();
new Thread(new SellerThread(pt.getResource())).start();
}
}

你可能感兴趣的:(多线程)