首页 > 代码库 > 多线程生产者消费者模式
多线程生产者消费者模式
闲着没事,写了个生产者消费者模式玩玩,顺便熟悉下notify的用法。
package sync; public class Test { public static void main(String[] args) { Test test = new Test(); Producer producer = test.new Producer(); producer.start(); Consumer consumer = test.new Consumer(); consumer.setName("consumer 0======"); consumer.start(); Consumer consumer1 = test.new Consumer(); consumer1.setName("consumer 1======"); consumer1.start(); Consumer consumer2 = test.new Consumer(); consumer2.setName("consumer 2======"); consumer2.start(); } /** * @Desc 仓库 (这是个内部静态类) * @author liuxingmi * @QQ 63972012 */ static class Factory { volatile int count = 0; boolean flag = true; private static Factory instance = new Factory(); public static Factory getInstance(){ if(instance == null){ instance = new Factory(); } return instance; } public synchronized void producer() { if (count >= 5) { flag = false; this.notifyAll(); try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } count++; System.out.println("producer count = " + count); try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public synchronized void consumer() { if (!flag) { System.out.println( Thread.currentThread().getName() + "start count = " + count + " times:" + System.currentTimeMillis()); if (count <= 0) { try { flag = true; this.notify(); this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } if(count > 0){//这个地方一定要判断,因为notify是随机唤醒线程,如果不判断在一个生产者,多个消费者情况下会出现负数的情况 count--; System.out.println( Thread.currentThread().getName() + " count = " + count); } try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } /** * @Desc 生产者 * @author liuxingmi * @QQ 63972012 */ class Producer extends Thread { Factory factory = Factory.getInstance(); @Override public void run() { while (true) { factory.producer(); } } } /** * @Desc 消费者 * @author liuxingmi * @QQ 63972012 */ class Consumer extends Thread { Factory factory = Factory.getInstance(); @Override public void run() { while (true) { factory.consumer(); } } } }
多线程生产者消费者模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。