package mypackage;
public class NumberStore {
private int data;
private boolean haveData;
public synchronized int getData(){
while(haveData==false) {
try {
wait();
}catch(InterruptedException e) {}
}
haveData=false;
notify();
return data;
}
public synchronized void putData(int value){
while(haveData==true) {
try {
wait();
}catch(InterruptedException e) {}
}
data=value;
notify();
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)(400*Math.random()));//休眠一段时间
}catch(InterruptedException e){}
}
}
}