生产者消费者模式的组成:
产品:生产者需要生产的产品。
生产池:根据生产池中产品的数量,确定是否进行生产和消费。
生产者:只负责给生产池生产产品。
消费者:只负责从生产池消费产品。
定义一个产品:
public class Product {
private String name;
public Product(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
生产池
public class Productpool {
private List<Product> productList = null;
private int maxSize = 0;
public Productpool(int maxSize) {
this.maxSize = maxSize;
productList = new LinkedList<Product>();
}
public synchronized void push(Product product) {
if (this.productList.size() == maxSize) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.productList.add(product);
System.out.println("生产了"+product.getName());
this.notifyAll();
}
public synchronized Product pop() {
if (this.productList.size() == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Product product = this.productList.remove(0);
System.out.println("消费了"+product.getName());
this.notifyAll();
return product;
}
}
生产者:
public class Producter extends Thread {
private Productpool productpool = null;
private int i = 0;
public Producter(Productpool productpool) {
this.productpool = productpool;
}
@Override
public void run() {
while (true) {
if (i >= 100) {
break;
}
String name = ++i + "号产品";
Product product = new Product(name);
this.productpool.push(product);
}
}
}
消费者
public class Comsumer extends Thread {
private Productpool productpool = null;
public Comsumer(Productpool productpool) {
this.productpool = productpool;
}
@Override
public void run() {
while (true) {
Product p = this.productpool.pop();
}
}
}
启动类
public class Progame {
public static void main(String[] args) {
Productpool productpool = new Productpool(10);
new Producter(productpool).start();
new Comsumer(productpool).start();
}
}
网友评论