场景:有一个盘子,最多可放4个苹果。
- 生产者往盘子里放苹果,若盘子满则生产者等待,否则放入一个苹果,并通知消费者消费;
- 消费者从盘子里取苹果,若盘子空则消费者等待,否则取走一个苹果,并通知生产者生产。
package org.iti.thread;
import java.util.ArrayList;
import java.util.List;
public class ThreadDemo_3 {
public static void main(String args[]) {
Plate plate = new Plate();
for (int i = 0; i < 15; i++) {
new Thread(new AddThread(plate)).start();
new Thread(new GetThread(plate)).start();
}
}
}
class AddThread implements Runnable {
private Plate plate;
private Object apple = new Object();
public AddThread(Plate plate) {
this.plate = plate;
}
public void run() {
plate.putApple(apple);
}
}
class GetThread implements Runnable {
private Plate plate;
public GetThread(Plate plate) {
this.plate = plate;
}
public void run() {
plate.getApple();
}
}
class Plate {
List<Object> apples = new ArrayList<Object>();
public synchronized Object getApple() {
while (apples.size() == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Object apple = apples.get(0);
apples.remove(apple);
notify();
System.out.println("拿到苹果");
return apple;
}
public synchronized void putApple(Object apple) {
while (apples.size() > 3) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
apples.add(apple);
notify();
System.out.println("放入苹果");
}
}