public class ProductLine {
Object[] ts;
int index;
public ProductLine(int capacity) {
this.ts = new Object[capacity];
}
//生产
public synchronized void push(Object t){
while(index == ts.length){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
ts[index ++ ] = t;
}
//消费
public synchronized Object pop(){
while(index == 0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
return ts[--index];
}
}
生产者:public class Producer implements Runnable {
int id;
private ProductLine pl;
Producer(int id, ProductLine pl) {
this.id = id;
this.pl = pl;
}
@Override
public void run() {
int i = 1;
for(int j=0; j<60; j++) {
pl.push(new Product(i++));
System.out.println("p" + id + " produce " + (i-1));
try {
Thread.sleep((int) (Math.random() * 200));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Consummer implements Runnable {
int id;
private ProductLine pl;
Consummer(int id, ProductLine pl) {
this.id = id;
this.pl = pl;
}
@Override
public void run() {
for(int j=0; j<20; j++) {
Product p = (Product)pl.pop();
System.out.println("c" + id + " consumme " + p.id);
try {
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
产品:public class Product {
int id = -1;
public Product(int id) {
super();
this.id = id;
}
}public class Test_Producer_Consummer {
public static void main(String[] args) {
ProductLine pl = new ProductLine(10);
Thread p1 = new Thread(new Producer(1, pl));
Thread c1 = new Thread(new Consummer(1, pl));
Thread c2 = new Thread(new Consummer(2, pl));
Thread c3 = new Thread(new Consummer(3, pl));
p1.start();
c1.start();
c2.start();
c3.start();
}
}
原文地址:http://blog.csdn.net/dafeng_blog/article/details/38357853