生产消费

来源:互联网 发布:淘宝怎么弄全球购图标 编辑:程序博客网 时间:2024/05/02 06:02
在Java程序中,生产消费问题能很好的解说明线程问题,这也是一个很典型的例子,我们就下面的代码来详细说明
package sync;public class ProducerConsumer {public static void main(String args[]){SyncStack ss = new SyncStack();Producer p = new Producer (ss);Consumer c = new Consumer (ss);Thread t1 = new Thread(p);Thread t2 = new Thread(c);t1.start();t2.start();}}class tomato{//食物类int id;tomato(int id){this.id = id;}public String toString(){return "tomato:"+id;}}class SyncStack{//生产和消费进程int num = 0;tomato []tmt = new tomato[6];public synchronized void push(tomato t){//生产的方法while(num == tmt.length){try{this.wait();}catch(InterruptedException q){q.printStackTrace();}}this.notify();tmt[num] = t;num++;}public synchronized tomato pop(){//消费的方法while(num == 0){try{this.wait();}catch(InterruptedException q){q.printStackTrace();}}this.notify();num--;return tmt[num];}}class Producer implements Runnable{//生产线程SyncStack ss = null;Producer(SyncStack ss){this.ss = ss;}public void run(){//生产的runfor(int i=0;i<20;i++){tomato t = new tomato(i);ss.push(t);System.out.println("生产了"+t);try{Thread.sleep((int)Math.random()*100);}catch(InterruptedException q){q.printStackTrace();}  }}} class Consumer implements Runnable{//消费线程SyncStack ss = null;Consumer(SyncStack ss){this.ss = ss;}public void run(){//消费的runfor(int i=0;i<20;i++){tomato t = new tomato(i);ss.pop();System.out.println("消费了"+t);try{Thread.sleep((int)Math.random()*100);}catch(InterruptedException q){q.printStackTrace();}}}}
<img src="http://img.blog.csdn.net/20150903220956716?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" /><img src="http://img.blog.csdn.net/20150903221112604?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
0 0