多个生产者多个消费者多个缓冲区

public class NumberStore {
	private int data;
	private boolean haveData;
	public synchronized int getData(){
		haveData=false;
		return data;
	}
	public synchronized void putData(int value){
		data=value;
		haveData=true;
	}
}

package mypackage;
class Consumer implements Runnable{
	private String name;
	private NumberStore myNumberStore;
	public Consumer(String n,NumberStore m){
		name=n;
		myNumberStore=m;
	}
	public void run(){
		int number;
		for(int i=0;i<10;i++){
			number=myNumberStore.getData();
			System.out.println("Consumer"+name+"get data:"+number);
			 try{
	    	    	Thread.sleep((int)(200*Math.random()));//休眠一段时间
	    	    }catch(InterruptedException e){}
		}
	}

}

package mypackage;
public class TestMultiThread {
	public static void main(String[] args) {
         NumberStore myNumber=new NumberStore();
         Producer p=new Producer("I",myNumber);
         Consumer c=new Consumer("I",myNumber);
         Thread myProducer=new Thread(p);
         Thread myConsumer=new Thread(c);
         myConsumer.start();
         myProducer.start();


	}

}

package mypackage;
class Producer implements Runnable{
    String name;
    private NumberStore myNumberStore;
    public Producer(String n,NumberStore m){
    	name=n;
    	myNumberStore=m;
    }
    public void run(){
    	int number;
    	for(int i=0;i<10;i++){
    		number=(int)(100*Math.random());
    	    System.out.println("Producer"+name+"produce number:"+number);
    	    myNumberStore.putData(number);
    	    try{
    	    	Thread.sleep((int)(200*Math.random()));//休眠一段时间
    	    }catch(InterruptedException e){}
    	}
    }

}
posted @ 2022-05-10 12:36  亚1918  阅读(25)  评论(0编辑  收藏  举报