无敌小火龙🔥☞ aa1213636414
关注数: 25 粉丝数: 134 发帖数: 2,858 关注贴吧数: 69
大佬们 帮帮忙 我这哪里有问题啊。。。 public class TestProduceConsumer { /*测试生产者消费者模式*/ public static void main(String[] args) { SyncStack syncStack=new SyncStack();//定义缓冲区 Consumer consumer=new Consumer(syncStack);//消费者线程 Produce produce=new Produce(syncStack);//生产者线程 produce.start(); consumer.start(); } } //馒头类 class Mantou{ int id; public Mantou (int id){ this.id=id; } } //缓冲区 (馒头框) class SyncStack{ //push 压栈,pop出栈 int index=0; Mantou[] ms=new Mantou[10]; public synchronized void push(Mantou mantou){ while (index ==ms.length){//说明馒头框满了 try { //调用wait后 线程会将持有的对象锁释放 进入等待池 //这样 锁池中的其他线程就能竞争获得对象锁 this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } //唤醒当前对象的等待池中的一个线程进入当前对象 this.notify(); } ms[index]=mantou; index++; } public synchronized Mantou pop(){ while (index==0){//框空了 try { //如果空了 消费线程进入等待 this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notify(); index--; return ms[index]; } } class Produce extends Thread{//生产者线程 SyncStack ss=null; public Produce(SyncStack ss){ this.ss=ss; } @Override public void run() { for (int i=0;i<10;i++){ System.out.println("生产馒头:"+i); Mantou m=new Mantou(i); ss.push(m); } } } class Consumer extends Thread{ SyncStack ss=null; public Consumer(SyncStack ss){ this.ss=ss; } public void run() { for (int i=0;i<10;i++){ Mantou m=ss.pop(); System.out.println("消费馒头"+m.id); } } }
1 下一页