生产者消费者问题

来源:互联网 发布:淘宝怎么看买家评星 编辑:程序博客网 时间:2024/06/05 19:14


package synchronizedpractise;public class ProducerCustomer{public static void main(String[] args){SynStack ss = new SynStack();Thread pro = new Thread(new Producer(ss));Thread cus = new Thread(new Customer(ss));pro.start();cus.start();while(pro.isAlive() == true || cus.isAlive() == true){}for(int i = 0; i < ss.index; i++){System.out.println(ss.breadList[i]);}}}class Bread{int id;public Bread(int i){this.id = i;}public String toString(){return "Bread " + id;}}class SynStack{int index;Bread[] breadList = new Bread[6];public synchronized void push(Bread br) throws InterruptedException{while (index == breadList.length){this.wait();}this.notify();breadList[index] = br;System.out.println("producer " + br + "  breadList[" + index + "]");index++;}public synchronized Bread pop() throws InterruptedException{while (index == 0){this.wait();}this.notify();index--;Bread br = breadList[index];System.out.println("customer " + breadList[index] + " breadList[" + index + "]");return br;}}class Producer implements Runnable{SynStack ss = new SynStack();public Producer(SynStack ss){this.ss = ss;}public void run(){for(int i = 0; i < 20; i++){try{Bread br = new Bread(i);ss.push(br);}catch (InterruptedException e){e.printStackTrace();}}}}class Customer implements Runnable{SynStack ss = new SynStack();public Customer(SynStack ss){this.ss = ss;}public void run(){for(int i = 0; i < 17; i++){try{ss.pop();}catch (InterruptedException e){e.printStackTrace();}}}}


0 0
原创粉丝点击