public class PandC { public static void main(String[] args) { new Thread(new Producer(),"生产者").start(); new Thread(new Consumer(),"消费者").start(); } } //通过单例模式 保证资源唯一 class Resource{ private String name; private int count; private boolean flag=false; static Resource r = new Resource(); private Resource() { } public static Resource getRes(){ return r; } public synchronized void produce(String name){ if(!flag) try { wait();//this.wait(); //this可省略 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } name = name+count++; flag=false; System.out.println(Thread.currentThread().getName()+" .........生产商品:"+count); this.notify();//this可省略 } public synchronized void consume(){ if(flag) try { wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } flag=true; System.out.println(Thread.currentThread().getName()+" ======消费商品:"+count); notify(); } } class Producer implements Runnable{ Resource r = Resource.getRes(); @Override public void run() { while(true) r.produce("商品:"); } } class Consumer implements Runnable{ Resource r = Resource.getRes(); @Override public void run() { while(true) r.consume(); } }
本文出自 “要么拼命,要么滚回去!” 博客,请务必保留此出处http://jiangzuun2014.blog.51cto.com/8732469/1441229