这篇文章主要讲解了“Java多线程中消费者生产者模式怎么实现”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Java多线程中消费者生产者模式怎么实现”吧!
//主类 class ProducerConsumer { public static void main(String[] args) { StackBasket s = new StackBasket(); Producer p = new Producer(s); Consumer c = new Consumer(s); Thread tp = new Thread(p); Thread tc = new Thread(c); tp.start(); tc.start(); } } // class Mantou { private int id; Mantou(int id){ this.id = id; } public String toString(){ return "Mantou :" + id; } } //共享栈空间 class StackBasket { Mantou sm[] = new Mantou[6]; int index = 0; public synchronized void push(Mantou m){ try{ while(index == sm.length){ System.out.println("!!!!!!!!!生产满了!!!!!!!!!"); this.wait(); } this.notify(); }catch(InterruptedException e){ e.printStackTrace(); }catch(IllegalMonitorStateException e){ e.printStackTrace(); } sm[index] = m; index++; System.out.println("生产了:" + m + " 共" + index + "个馒头"); } public synchronized Mantou pop(){ try{ while(index == 0){ System.out.println("!!!!!!!!!消费光了!!!!!!!!!"); this.wait(); } this.notify(); }catch(InterruptedException e){ e.printStackTrace(); }catch(IllegalMonitorStateException e){ e.printStackTrace(); } index--; System.out.println("消费了:---------" + sm[index] + " 共" + index + "个馒头"); return sm[index]; } } class Producer implements Runnable { StackBasket ss = new StackBasket(); Producer(StackBasket ss){ this.ss = ss; } public void run(){ for(int i = 0;i < 20;i++){ Mantou m = new Mantou(i); ss.push(m); // System.out.println("生产了:" + m + " 共" + ss.index + "个馒头"); // 在上面一行进行测试是不妥的,对index的访问应该在原子操作里,因为可能在push之后此输出之前又消费了,会产生输出混乱 try{ Thread.sleep((int)(Math.random()*500)); }catch(InterruptedException e){ e.printStackTrace(); } } } } class Consumer implements Runnable { StackBasket ss = new StackBasket(); Consumer(StackBasket ss){ this.ss = ss; } public void run(){ for(int i = 0;i < 20;i++){ Mantou m = ss.pop(); // System.out.println("消费了:---------" + m + " 共" + ss.index + "个馒头"); // 同上 在上面一行进行测试也是不妥的,对index的访问应该在原子操作里,因为可能在pop之后此输出之前又生产了,会产生输出混乱 try{ Thread.sleep((int)(Math.random()*1000)); }catch(InterruptedException e){ e.printStackTrace(); } } } }
感谢各位的阅读,以上就是“Java多线程中消费者生产者模式怎么实现”的内容了,经过本文的学习后,相信大家对Java多线程中消费者生产者模式怎么实现这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!