四个类
- 生产者
import java.util.Date;
import java.util.LinkedList;
public class Storage {
private Integer maxSize;
private LinkedList<Date> queue;
public Storage() {
maxSize = 10;
queue = new LinkedList<>();
}
public synchronized void put() {
while (queue.size() == maxSize) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.offer(new Date());
System.out.println("仓库里有了 " + queue.size() + " 个产品");
notify();
}
public synchronized void take() {
while (queue.isEmpty()) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("拿到了 " + queue.poll() + ",仓库还剩下 " + queue.size() + " 个产品");
notify();
}
}
- 生产者
public class Producer implements Runnable {
private Storage storage;
public Producer(Storage storage) {
this.storage = storage;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
storage.put();
}
}
}
- 消费者
public class Consumer implements Runnable {
private Storage storage;
public Consumer(Storage storage) {
this.storage = storage;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
storage.take();
}
}
}
- 测试类
public class Test {
public static void main(String[] args) {
Storage storage = new Storage();
Consumer consumer = new Consumer(storage);
Producer producer= new Producer(storage);
new Thread(consumer).start();
new Thread(producer).start();
}
}