多线程之生产者与消费者问题
来源:互联网 发布:asp.net入门编程实例 编辑:程序博客网 时间:2024/05/17 06:20
生产者生产产品后将产品放在一个仓库里,消费者购买省商品相当于从仓库里拿出商品。这其中涉及到的有生产者、消费者与仓库以及产品四个对象,因此需要创建四个类来表示。最后还需要一个测试类。对于生成与消费这两个动作可是是同时执行的(只要有商品的话),因此需要使用到多线程的知识。
product类 public class Product{ private int id;//根据id来标识产产品 public Product41(int id) { this.id = id; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
Storage类public class Storage{ Product[] ps = new Product[10];//该仓库只可以装10件商品 int index; //因为不止一个生产者生产产品,所以向仓库中添加商品的方法需要 //使用到锁的机制(synchoronized) public synchronized void push(Prodeuct p){ //如果仓库已经装满了产品那么就停止生产 while(index == ps.length){ try { this.wait();//暂停该线程 } catch (InterruptedException e) { e.printStackTrace(); } } this.notifyAll();//唤醒该线程 ps[index] = p; index++; } //取出产品的方法 public synchronized Product pop(){ while (index == 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notifyAll(); index--; return ps[index]; }}
Producer类 public class Producer extends Thread{ Storage storage;//生产者需要将生产出来的产品放在仓库 public Producer(Storage storage){ this.storage = storage; } //因为继承了Thread类,所以需要重写Run方法 @override public void run(){ System.out.println("生产者"+getName()+"生产了一件商品"); Product p = new Product(i);//生产一件产品 storage.push(p);//将产品添加到仓库 try{ sleep(300); }catch(InterruptedException e){ e.printStackTrace(); } } }
Customer类public class Customer extends Thread{ Storage storage;//消费者需要从仓库中取出产品 public Customer(Storage storage){ this.storage = storage; } @override public void run(){ for(int i = 0; i < 20; i++){ //从仓库中取出产品 Product p = storage.pop(); System.out.println("消费者"+getName()+"消费了一件产品"); try { sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } } }}
TestMain类public class Test{ public static void main(String[] args){ //建立一个仓库 Storage s = new Storage(); //创建生产者与消费者 Customer c1 = new Customer(s); //为该线程设置一个名字 c1.setName("c1"); Customer c2 = new Customer(s); c2.setName("c2"); Producer p1 = new Producer(s); p1.setName("p1"); Producer p2 = new Producer(s); p2.setName("p2"); //启动线程 p1.start(); p2.start(); c1.start(); c2.start(); }}
阅读全文
0 0
- 多线程之生产者与消费者问题
- 多线程之生产者与消费者问题
- 多线程之生产者与消费者问题
- 多线程-生产者与消费者问题
- 多线程之生产者消费者问题
- 多线程之生产者消费者问题
- 多线程之生产者消费者问题
- 多线程之生产者消费者问题
- java多线程之生产者与消费者问题的简单模拟
- java多线程之生产者与消费者问题的简单模拟
- JAVA多线程实例(生产者与消费者问题)
- 多线程生产者与消费者问题的总结
- java多线程同步:生产者与消费者问题
- 多线程经典问题-生产者与消费者
- Java多线程--生产者与消费者问题
- Boost多线程实现生产者与消费者问题
- 多线程解决生产者与消费者问题
- Java经典多线程问题--生产者与消费者
- Android O新特性
- 并查集入门学习
- (笔记)初步了解监督学习
- Apache从HTTP到HTTPS的实现
- ant脚本使用multidex解决65536问题
- 多线程之生产者与消费者问题
- LSTM初探
- 一张图让你搞懂JavaScript的继承与原型链
- 后缀自动机模板
- ROS包编译错误一例“ return m.__getMD5Sum().c_str();”
- Brackets sequence UVA
- 函数调用过程解析图
- 图像I、P、B帧介绍
- python,requests基础