两道企业面试题(2)-生产者消费者问题

来源:互联网 发布:end.js 编辑:程序博客网 时间:2024/05/29 03:38
/* *   生产者消费者问题 */public class ProducerConsumer {public static void main(String[] args){SyncStack ss=new SyncStack();//两个线程访问同一个框Producer p=new Producer(ss);Consumer c=new Consumer(ss);new Thread(p).start();new Thread(c).start();}}//馒头class WoTou{int id;WoTou (int id){this.id=id;}public String toString(){return "WoTou:"+id;}}//放馒头的框class SyncStack{int index=0;WoTou[] arrWT=new WoTou[6];//生产者往框里放入馒头public synchronized void push(WoTou wt){//如果当前框里已经满了,则休息一会while(index==arrWT.length){try{    this.wait();}catch (InterruptedException e){e.printStackTrace();}}//将线程唤醒this.notify();arrWT[index]=wt;index++;}//消费者从框里拿出馒头public synchronized WoTou pop(){//同样,当框里没有馒头了,则休息一会while(index==0){try{    this.wait();    }catch (InterruptedException e){    e.printStackTrace();    }}this.notify();index--;return arrWT[index];}}//生产者class Producer implements Runnable{    SyncStack ss=null;    Producer(SyncStack ss){    this.ss=ss;    }    //把馒头放进框里public void run() {for(int i=0;i<20;i++){WoTou wt=new WoTou(i);ss.push(wt);System.out.println("生产了:"+wt);//生产一个休息一秒钟try{Thread.sleep((int)(Math.random()*1000));}catch (InterruptedException e){e.printStackTrace();}}}}//消费者class Consumer implements Runnable{    SyncStack ss=null;    Consumer(SyncStack ss){    this.ss=ss;    }    //把馒头放进框里public void run() {for(int i=0;i<20;i++){WoTou wt=ss.pop();//将返回值打印出来,但看不到WoTou的id,可以重写它的toString方法System.out.println("消费了:"+wt);try{Thread.sleep((int)(Math.random()*1000));}catch (InterruptedException e){e.printStackTrace();}}}}

运行结果:

消费了:WoTou:0生产了:WoTou:0生产了:WoTou:1消费了:WoTou:1生产了:WoTou:2生产了:WoTou:3消费了:WoTou:3消费了:WoTou:2生产了:WoTou:4消费了:WoTou:4生产了:WoTou:5消费了:WoTou:5生产了:WoTou:6生产了:WoTou:7消费了:WoTou:7消费了:WoTou:6生产了:WoTou:8消费了:WoTou:8生产了:WoTou:9消费了:WoTou:9生产了:WoTou:10消费了:WoTou:10生产了:WoTou:11生产了:WoTou:12消费了:WoTou:12生产了:WoTou:13消费了:WoTou:13消费了:WoTou:11生产了:WoTou:14消费了:WoTou:14生产了:WoTou:15消费了:WoTou:15消费了:WoTou:16生产了:WoTou:16生产了:WoTou:17消费了:WoTou:17生产了:WoTou:18消费了:WoTou:18生产了:WoTou:19消费了:WoTou:19


0 0