这里运用产品-店员-消费者的例子来说明这两个函数
店员类
public class Clerk {
private int product = -1;
public synchronized void setProduct(int product) throws InterruptedException {
waitIfFull();
this.product = product;
System.out.printf("生产者设定 (%d) %n", this.product);
notify();
}
private synchronized void waitIfFull() throws InterruptedException {
while (this.product != -1) {
wait();
}
}
public synchronized int getProduct() throws InterruptedException {
waitIfEmpty();
int pro = this.product;
this.product = -1;
System.out.printf("消费者取走 (%d)%n", pro);
notify();
return pro;
}
private void waitIfEmpty() throws InterruptedException {
while (this.product == -1) {
wait();
}
}
}
产品类
public class Producer implements Runnable {
private Clerk clerk;
public Producer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
System.out.println("生产者开始生产整数...");
for (int i = 1; i <= 10; i++) {
try {
clerk.setProduct(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
消费者
public class Consumer implements Runnable {
private Clerk clerk;
public Consumer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
System.out.println("消费者开始消耗整数...");
for (int i = 1; i <= 10; i++) {
try {
clerk.getProduct();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
测试类
public class Main {
public static void main(String[] args) {
Clerk clerk = new Clerk();
new Thread(new Producer(clerk)).start();
new Thread(new Consumer(clerk)).start();
}
}
输出结果
生产者开始生产整数...
消费者开始消耗整数...
生产者设定 (1)
消费者取走 (1)
生产者设定 (2)
消费者取走 (2)
生产者设定 (3)
消费者取走 (3)
生产者设定 (4)
消费者取走 (4)
生产者设定 (5)
消费者取走 (5)
生产者设定 (6)
消费者取走 (6)
生产者设定 (7)
消费者取走 (7)
生产者设定 (8)
消费者取走 (8)
生产者设定 (9)
消费者取走 (9)
生产者设定 (10)
消费者取走 (10)