Java实现生产者消费者问题
作者:网络转载 发布时间:[ 2016/3/11 14:20:31 ] 推荐标签:测试开发技术 编程语言
引言
生产者和消费者问题是线程模型中的经典问题:生产者和消费者在同一时间段内共用同一个存储空间,如下图所示,生产者向空间里存放数据,而消费者取用数据,如果不加以协调可能会出现以下情况:
生产者消费者图
存储空间已满,而生产者占用着它,消费者等着生产者让出空间从而去除产品,生产者等着消费者消费产品,从而向空间中添加产品。互相等待,从而发生死锁。
JAVA解决线程模型的三种方式
1、wait()和notify()
import java.util.LinkedList;
public class ProducerConsumer {
private LinkedList<Object> storeHouse = new LinkedList<Object>();
private int MAX = 10;
public ProducerConsumer() {
}
public void start() {
new Producer().start();
new Comsumer().start();
}
class Producer extends Thread {
public void run() {
while (true) {
synchronized (storeHouse) {
try {
while (storeHouse.size() == MAX) {
System.out.println("storeHouse is full , please wait");
storeHouse.wait();
}
Object newOb = new Object();
if (storeHouse.add(newOb)) {
System.out.println("Producer put a Object to storeHouse");
Thread.sleep((long) (Math.random() * 3000));
storeHouse.notify();
}
} catch (InterruptedException ie) {
System.out.println("producer is interrupted!");
}
}
}
}
}
class Comsumer extends Thread {
public void run() {
while (true) {
synchronized (storeHouse) {
try {
while (storeHouse.size() == 0) {
System.out.println("storeHouse is empty , please wait");
storeHouse.wait();
}
storeHouse.removeLast();
System.out.println("Comsumer get a Object from storeHouse");
Thread.sleep((long) (Math.random() * 3000));
storeHouse.notify();
} catch (InterruptedException ie) {
System.out.println("Consumer is interrupted");
}
}
}
}
}
public static void main(String[] args) throws Exception {
ProducerConsumer pc = new ProducerConsumer();
pc.start();
}
}
相关推荐
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11