多线程之生产者消费者问题

来源:互联网 发布:软件系统技术方案 编辑:程序博客网 时间:2024/05/16 06:08

生产者:producer;

消费者consumer;

篮子:basket_stack(以栈结构代替的篮子,丢进去的馒头满足先进后出)

问题描述:生产者生产10个馒头丢进容量只有6的篮子里面,消费者不断吃掉篮子中的馒头。

package consumer_producer;public class consumer_producer {public static void main(String[] args){Basket_stack bs = new Basket_stack();Producer p = new Producer(bs);Consumer c = new Consumer(bs);new Thread(p).start();new Thread(c).start();}}class ManTou{int id=0;ManTou(int id){this.id=id;}}class Basket_stack{int index=0;ManTou[] mt_stack = new ManTou[6];public synchronized void push(ManTou mt){while(index == mt_stack.length){try {this.wait();} catch (InterruptedException e) {// TODO: handle exceptione.printStackTrace();}}this.notify();mt_stack[index]=mt;index++;}public synchronized ManTou pop(){while(index == 0){try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}this.notify();index--;return mt_stack[index];}}class Producer implements Runnable{Basket_stack bs = null;Producer(Basket_stack bs){this.bs=bs;}public void run(){for(int i=1;i<=10;i++){synchronized (bs) {ManTou mt = new ManTou(i);bs.push(mt);System.out.println("生产了馒头:"+mt.id);try {Thread.sleep((int)(Math.random()*1000));} catch (InterruptedException e) {e.printStackTrace();}}}}}class Consumer implements Runnable{Basket_stack bs = null;Consumer(Basket_stack bs){this.bs=bs;}public void run(){for(int i=0;i<10;i++){synchronized (bs) {ManTou mt = bs.pop();System.out.println("消费了馒头:"+mt.id);try {Thread.sleep((int)(Math.random()*200));} catch (InterruptedException e) {e.printStackTrace();}}}}}
运行结果:


0 0
原创粉丝点击