首页 > 代码库 > 生产者消费者问题
生产者消费者问题
如问题的名字那样,首先要有个生产者和消费者,所以需要定义两个class来分别描述他们的特点。
/** * 生产者线程类 */ class Producer implements Runnable { /** 持有容器 */ private Can c = null; public Producer(Can c) { this.c = c; } @Override public void run() { while (true) { // 生产一个产品 Production p = new Production(); System.out.println(p + "被生产了。"); // 将产品存入容器 try { c.push(p); System.out.println(p + "被放入容器。"); } catch (InterruptedException e) { e.printStackTrace(); } } } }
/** * 消费者线程类 */ class Consumer implements Runnable{ /** 持有容器 */ private Can c = null; public Consumer(Can c) { this.c = c; } @Override public void run() { while (true) { // 从容器取出一个产品 Production p = null; try { p = c.pop(); System.out.println(p + "从容器取出。"); // 消费一个产品 System.out.println(p + "被毁灭了。"); } catch (InterruptedException e) { e.printStackTrace(); } } } }
紧接着,生产者和消费者是通过“产品”联系起来,所以还需要定义一个描述“产品”的POJO。
/** * 产品的实体类 */ class Production { /** 识别No. */ private int no = 0; private static int counter = 0; public Production() { no = counter++; } public String toString() { return no + "号产品"; } }
最后是临时容纳“产品”的容器,它应该通过栈来实现,同时它的实例还被许多生产者实例和消费者实例,这些实例都象征着一个线程。
/** * 用栈实现的容器类 */ class Can { /** 栈顶指针 */ private int pointer = 0; /** 内部持有对象的数组 */ private Production[] productions = {null, null, null, null, null, null}; /** 压入一个元素 */ public synchronized void push(Production p) throws InterruptedException { while (pointer == 6) { wait(); } productions[pointer++] = p; notifyAll(); } /** 弹出一个元素 */ public synchronized Production pop() throws InterruptedException { while (pointer == 0) { wait(); } Production p = productions[--pointer]; notifyAll(); return p; } }
生产者消费者问题
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。