这篇直接贴代码了
package cn.javaBase.study_thread1; class Source { public static int num = 0; //假设这是馒头的数量 } class Producer implements Runnable { private Object obj; public Producer(Object obj) { this.obj = obj; } @Override public void run() { synchronized (obj) { while (true) { if (Source.num >= 6) { //馒头的数量>=6个的时候,就停下来不生产了,通知别人来消费 obj.notify(); System.out.println("满了,消费吧"); try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } Source.num++; System.out.println("已经生产了:"+ Source.num + "个"); } } } } class Consumer implements Runnable{ private Object obj; public Consumer(Object obj) { this.obj = obj; } @Override public void run() { synchronized (obj) { while (true) { if (Source.num == 0) { //馒头的数量==0个的时候,就停下不消费了,通知别人该生产了 obj.notify(); System.out.println("没了,生产吧。"); try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } Source.num--; System.out.println("剩下了:"+ Source.num + "个"); } } } } public class MyProducerConsumer { public static void main(String[] args) throws InterruptedException { Object a = new Object(); Producer p = new Producer(a); Consumer c = new Consumer(a); new Thread(p).start(); Thread.sleep(200); //为了保证先生产,再消费, 不用也可以 new Thread(c).start(); } }
因为思想跟上一篇的Java多线程之wait和notify:http://www.cnblogs.com/WNof11020520/p/8780875.html
讲的差不多,所以在这里就不累赘了。