class Storage {//仓库类,用于生产产品和消费产品
int n;
boolean valueSet = false;
synchronized int get() {
//消费产品
while(!valueSet)
try {
wait();
//消费者消耗了产品后需要wait,来等待生产者生产产品
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Got: " + n);
valueSet = false;
notify();
//当产品消费了之后,需要唤醒被wait的put()来生产产品
return n;
}
synchronized void put(int n) {
//生产产品
while(valueSet)
try {
wait();
//当valueSet为true时,停止生产产品
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Put: " + n);
notify();
//put()生产了产品后需要唤醒消费者去get()消耗产品
}
}
class Producer implements Runnable {
Storage q;
Producer(Storage q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
q.put(i++);
}
}
}
class Consumer implements Runnable {
Storage q;
Consumer(Storage q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
q.get();
}
}
}
class consumer_producer {
public static void main(String args[]) {
Storage q = new Storage();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}