1、生产者与消费者问题的描述
一个或者多个生产者,一个或者多个消费者。生产者在一条生产线不停地生产产品,消费者们不停地消费产品,需要注意的是
这里的生产线属于临界资源(Critical Source).
当生产线的产品生产满之后,生产者不能再往生产线生产产品,当生产线为空时消费者不能往生产线消费产品。
生产线里面有两个方法,生产和消费,这两个方法都临界区(Critical Section),只能互斥访问。
2、java的实现
生产线:
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();
}
}

本文介绍了一个经典的并发编程问题——生产者消费者模式,并提供了一个使用Java实现的具体案例。该模式涉及多线程同步问题,通过生产线类实现产品生产和消费的同步控制。
1497

被折叠的 条评论
为什么被折叠?



