记一篇“生产者-消费者”多线程Java实例
1.ProducerConsumer.javapublic class ProducerConsumer {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ProductList ps = new ProductList();
Producer px = new Producer(ps, "生产者X");
Producer py = new Producer(ps, "生产者Y");
Consumer ca = new Consumer(ps, "消费者a");
Consumer cb = new Consumer(ps, "消费者b");
Consumer cc = new Consumer(ps, "消费者c");
new Thread(px).start();
new Thread(py).start();
new Thread(ca).start();
new Thread(cb).start();
new Thread(cc).start();
}
}
2.Product.java
public class Product {
int id;
private String producedBy = "N/A";
private String consumedBy = "N/A";
Product(String producedBy) {
this.producedBy = producedBy;
}
public void consume(String consumedBy) {
this.consumedBy = consumedBy;
}
public String toString() {
return "产品,生产者 = " + producedBy + ",消费者 =" + consumedBy;
}
public String getProducedBy() {
return producedBy;
}
public void setProducedBy(String producedBy) {
this.producedBy = producedBy;
}
public String getConsumedBy() {
return consumedBy;
}
public void setConsumedBy(String consumedBy) {
this.consumedBy = consumedBy;
}
}
3.ProductList.java
public class ProductList {
int index = 0;
Product []productList = new Product[6];
public synchronized void push(Product product) {
while(index == productList.length) {
try {
System.out.println(" " + product.getProducedBy() + "is waiting.");
wait();
}catch(InterruptedException e) {
e.printStackTrace();
}
}
productList[index] = product;
index++;
System.out.println(index + "" + product.getProducedBy() + "生产了:" + product);
notifyAll();
System.out.println(" " + product.getProducedBy() + "sent a notifyAll().");
}
public synchronized Product pop(String consumerName) {
while(index ==0) {
try {
System.out.println(" " + consumerName + "is waiting");
wait();
}catch(InterruptedException e) {
e.printStackTrace();
}
}
index--;
Product product = productList[index];
product.consume(consumerName);
System.out.println(index + "" + product.getConsumedBy() + "消费了:" + product);
notifyAll();
System.out.println(" " + consumerName + "sent a notifyAll().");
return product;
}
}
4.Producer.java
public class Producer implements Runnable {
String name;
ProductList ps = null;
Producer(ProductList ps, String name) {
this.ps = ps;
this.name = name;
}
public void run() {
while(true) {
Product product = new Product(name);
ps.push(product);
try {
Thread.sleep((int)(Math.random()*200));
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
5.Consumer.java
public class Consumer implements Runnable {
String name;
ProductList ps = null;
Consumer(ProductList ps, String name) {
this.ps = ps;
this.name = name;
}
public void run() {
while(true) {
ps.pop(name);
try {
Thread.sleep((int)(Math.random()*1000));
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}