您的位置:首页 > 其它

简单消费者生产者问题

2011-08-02 11:21 330 查看
import java.util.*;

public class HelloWorld {  
public static void main(String[] args){
dataStore m = new dataStore();
Producer p = new Producer("P",m);
Consumer c1= new Consumer("A",m);
Consumer c2= new Consumer("B",m);
Consumer c3= new Consumer("C",m);

Thread t1 = new Thread(c1);
Thread t2 = new Thread(c2);
Thread t3 = new Thread(c3);

        Thread t4 = new Thread(p);

        

        t1.start();

        t2.start();

        t3.start();

        t4.start();
}

}

class Producer implements Runnable{
String name ;
private dataStore myDataStore;

public Producer(String s, dataStore m){
name = s ;
myDataStore = m;
}

public void run(){
for(int i = 0 ;i < 15 ;i++ ){
int number = (int)(Math.random()*100);

myDataStore.putData(number,name);

}
try{
Thread.sleep((int)(200*Math.random()));
}
catch(InterruptedException e){}
}

}

class Consumer implements Runnable{
private String name ;
private dataStore myDataStore;

public Consumer(String s,dataStore m){
name = s ;
myDataStore = m;
}

public void run(){
int number;
for(int i = 0 ;i < 5 ;i++ ){
number = myDataStore.getData(name);

}

}

}

class  dataStore{
private int[] data = new int[4];
private int haveData = 0;

public synchronized int getData(String name){
while (haveData <= 0){
try{
wait();
}
catch (InterruptedException e ){}
}
haveData--;
notify();
System.out.println(" Consumer " + name + " consume the data " + data[haveData]);
return data[haveData];

    }
public synchronized void putData(int v,String name){
while(haveData >=3 ){
try{
wait();
}
catch(InterruptedException e){}
}
data[haveData] = v;
haveData++;
System.out.println(" Pro " + name + " produce the numble " + v );
notify();

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  thread string class import c