1. 使用wait()和notify()方法:
import java.util.LinkedList;
class ProducerConsumer {
private LinkedList<byte[]> buffer = new LinkedList<>();
private int capacity = 10;
public void produce() throws InterruptedException {
while (true) {
synchronized (this) {
while (buffer.size() == capacity) {
wait();
}
byte[] data = generateData();
buffer.add(data);
System.out.println("Produced: " + data.length + " bytes");
notify();
Thread.sleep(1000);
}
}
}
public void consume() throws InterruptedException {
while (true) {
synchronized (this) {
while (buffer.isEmpty()) {
wait();
}
byte[] data = buffer.removeFirst();
System.out.println("Consumed: " + data.length + " bytes");
notify();