标签:style blog http color io os ar java for
1 package producer; 2 3 public class SyncStack { 4 int index =0; 5 SteamedBun[] bunArr = new SteamedBun[6]; //栈里只能放6个元素 6 7 public synchronized void push(SteamedBun bun) 8 { 9 while(index >= bunArr.length) //栈满等待 10 { 11 bun.setIndex(bunArr.length -1); //修正馒头编号 12 try { 13 this.wait(); 14 } catch (InterruptedException e) { 15 // TODO Auto-generated catch block 16 e.printStackTrace(); 17 } 18 } 19 //this.notify(); //单个线程时调用 20 this.notifyAll(); //广播给所有大厨 21 22 bunArr[index] = bun; 23 index++; 24 } 25 26 public synchronized SteamedBun pop() 27 { 28 while(index ==0) //栈空,没有馒头时等待生产 29 { 30 try { 31 this.wait(); 32 } catch (InterruptedException e) { 33 // TODO Auto-generated catch block 34 e.printStackTrace(); 35 } 36 } 37 this.notify(); //通知吃货有馒头了 38 39 index--; 40 return bunArr[index]; 41 } 42 43 44 }
1 package producer; 2 3 public class Producer implements Runnable{ 4 SyncStack ss = null; 5 int pId; 6 public Producer(SyncStack ss,int pId) { 7 this.ss = ss; 8 this.pId = pId; 9 } 10 11 @Override 12 public void run() { 13 // TODO Auto-generated method stub 14 for(int i=0;i<10;i++) 15 { 16 SteamedBun bun = new SteamedBun(ss.index,pId*1000+i); 17 ss.push(bun); 18 System.out.println("****做了"+bun); 19 20 try { 21 int iRandom = (int)(Math.random()*2000); 22 Thread.sleep(iRandom); 23 } catch (InterruptedException e) { 24 // TODO Auto-generated catch block 25 e.printStackTrace(); 26 } 27 } 28 } 29 30 }
1 package producer; 2 3 public class Consumer implements Runnable{ 4 5 SyncStack ss = null; 6 public Consumer(SyncStack ss) 7 { 8 this.ss = ss; 9 } 10 11 @Override 12 public void run() { 13 // TODO Auto-generated method stub 14 for(int i= 0;i<30;i++) 15 { 16 SteamedBun bun = ss.pop(); 17 System.out.println("吃了 "+bun); 18 19 try { 20 Thread.sleep((int)(Math.random()* 1000)); 21 } catch (InterruptedException e) { 22 // TODO Auto-generated catch block 23 e.printStackTrace(); 24 } 25 } 26 } 27 28 }
1 package producer; 2 3 public class SteamedBun { 4 private int id; 5 private int index; 6 public SteamedBun(int index,int id) { 7 this.id = id; 8 this.index = index; 9 } 10 11 public String toString() 12 { 13 return "一个馒头,是筐里的第" + (index+1) + "个馒头,编号"+id; 14 } 15 16 public void setIndex(int index) { 17 this.index = index; 18 } 19 }
1 package producer; 2 3 public class Test { 4 public static void main(String[] args) { 5 SyncStack ss = new SyncStack(); 6 7 //new 3个大厨和1个吃货的线程 8 new Thread(new Producer(ss,1)).start(); 9 new Thread(new Producer(ss,2)).start(); 10 new Thread(new Producer(ss,3)).start(); 11 12 Consumer consumer = new Consumer(ss); 13 new Thread(consumer).start(); 14 } 15 }
标签:style blog http color io os ar java for
原文地址:http://www.cnblogs.com/fancyzhen/p/4009185.html