您的位置:首页 > 编程语言 > Java开发

Java线程:并发协作-生产者消费者模型

2013-04-10 22:40 435 查看
对于多线程程序来说,不管任何编程语言,生产者和消费者模型都是最经典的。

实际上,准确说应该是“生产者-消费者-仓储”模型,离开了仓储,生产者消费者模型就显得没有说服力了。

对于此模型,应该明确一下几点:

1、生产者仅仅在仓储未满时候生产,仓满则停止生产。

2、消费者仅仅在仓储有产品时候才能消费,仓空则等待。

3、当消费者发现仓储没产品可消费时候会通知生产者生产。

4、生产者在生产出可消费产品时候,应该通知等待的消费者去消费。

此模型将要结合java.lang.Object的wait与notify、notifyAll方法来实现以上的需求。这是非常重要的。

public class Test {
public static void main(String[] args) {
Godown godown = new Godown(30);
Consumer c1 = new Consumer(50, godown);
Consumer c2 = new Consumer(20, godown);
Consumer c3 = new Consumer(30, godown);
Producer p1 = new Producer(10, godown);
Producer p2 = new Producer(10, godown);
Producer p3 = new Producer(10, godown);
Producer p4 = new Producer(10, godown);
Producer p5 = new Producer(10, godown);
Producer p6 = new Producer(10, godown);
Producer p7 = new Producer(80, godown);

c1.start();
c2.start();
c3.start();
p1.start();
p2.start();
p3.start();
p4.start();
p5.start();
p6.start();
p7.start();
}
}


package com.xin;

/**
* 生产者
*/
public class Producer extends Thread {
private int neednum;                //生产产品的数量
private Godown godown;            //仓库

Producer(int neednum, Godown godown) {
this.neednum = neednum;
this.godown = godown;
}

public void run() {
//生产指定数量的产品
godown.increace(neednum);
}
}
package com.xin;

/**
* 仓库
*/
public class Godown {
public static final int max_size = 100; //最大库存量
public int curnum;     //当前库存量

Godown() {
}

Godown(int curnum) {
this.curnum = curnum;
}
/**
* 增加公共资源
*/
public synchronized void increace(int n) {
while (n + curnum > max_size) {
System.out.println("要生产的产品数量" + n + "超过剩余库存量" + (max_size - curnum) + ",暂时不能执行生产任务!");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
curnum+=n;
System.out.println("已经生产了" + n + "个产品,现仓储量为" + curnum);
notify();
}

/**
* 减少公共资源
*/
public synchronized void decreace(int n) {
while (curnum < n) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
curnum = curnum -n;
System.out.println("已经消费了" + n + "个产品,现仓储量为" + curnum) ;
notify();
}
}


package com.xin;

/**
* 消费者
*/
public class Consumer extends Thread {
private int neednum;                //生产产品的数量
private Godown godown;            //仓库

Consumer(int neednum, Godown godown) {
this.neednum = neednum;
this.godown = godown;
}

public void run() {
//消费指定数量的产品
godown.decreace(neednum);
}
}


要说明的是当发现不能满足生产或者消费条件的时候,调用对象的wait方法,wait方法的作用是释放当前线程的所获得的锁,并调用对象的notifyAll() 方法,通知(唤醒)该对象上其他等待线程,使得其继续执行。这样,整个生产者、消费者线程得以正确的协作执行。

notifyAll() 方法,起到的是一个通知作用,不释放锁,也不获取锁。只是告诉该对象上等待的线程“可以竞争执行了,都醒来去执行吧”。

wait() 等待资源 排队中

sleep(t) 过t时间之后再去排队

join() 插队

notify() 通知可以排队去竞争了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: