闲着没事,写了个生产者消费者模式玩玩,顺便熟悉下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(); } } } }
原文地址:http://blog.csdn.net/lxm63972012/article/details/39082001