package lock1;
import java.util.ArrayList;
import java.util.List;
class Producer implements Runnable {
private Products stack;
public Producer(Products stack) {
this.stack = stack;
}
@Override
public void run() {
while (true) {
stack.produce();
}
}
}
class Consumer implements Runnable {
private Products stack;
public Consumer(Products stack) {
this.stack = stack;
}
@Override
public void run() {
while (true) {
stack.consume();
}
}
}
class Products {
private static final long serialVersionUID = 1L;
private List<String> products = new ArrayList<String>();
private int capacity = 10;
public synchronized void produce() {
while (products.size() > capacity) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
String str = "生产者生产的产品!";
System.out.println(str);
products.add(str);
}
public synchronized void consume() {
while (products.size() == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
for (int i = 0; i < products.size(); i++) {
System.out.println("消费者shiyong :" + products.get(i));
products.remove(i);
}
}
}
public class ConsumerProducer {
public static void main(String[] args) throws InterruptedException {
Products products = new Products();
Producer producer = new Producer(products);
Consumer consumer = new Consumer(products);
new Thread(producer).start();
new Thread(consumer).start();
}
}