生产者-消费者问题(producer - consumer)是一个著名的进程同步问题;今天我们用加入“”等待与唤醒“”来解决。
package zz;
public class Producer extends Thread {
private Box box;
private String name;
public Producer(Box b, String n) {
box = b;
name = n;
}
public void run() {
for (int i = 1; i < 6; i++) {
box.put(i);
System.out.println("Producer " + name
+ " produed: " + i);
}
try {
sleep((int) (Math.random() * 100));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package zz;
class Consumer extends Thread {
private Box box;
private String name;
public Consumer(Box b, String n) {
box = b;
name = n;
}
public void run() {
int value = 0;
for (int i = 1; i < 6; i++) {
value = box.get();
System.out.println("Consumer " + name+ " consumed: " + value);
}
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package zz;
public class Box{
private int value;
private boolean available = false;
public synchronized int get() {//synchronized:给方法加锁
while (available == false) {
try {
//等待生产者写入数据
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
available = false;
//通知生产者数据已被取走,可以再次写入数据
notifyAll();
return value;
}
public synchronized void put(int value) {
while (available == true) {
try {
//等待消费者取走数据
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.value = value;
available = true;
//通知消费者可以来取数据
notifyAll();
}
}
package zz;
public class ProducerConsumerTest {
/**
* 生产者/消费者问题
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Box box = new Box();
Producer p = new Producer(box, "p");
Consumer c = new Consumer(box, "c");
p.start();
c.start();
}
}