首页 > 代码库 > 2014/9/28消费生产

2014/9/28消费生产

  1 package ha;  2 import java.io.*;  3 import java.util.*;  4   5 public class wori   6 {  7     public static void main(String args[])  8     {  9         holder h = new holder(); 10         new Thread(new shifu(h)).start(); 11         new Thread(new man(h)).start(); 12     } 13 } 14  15 class mantou  16 { 17     private int id; 18     mantou(int id) 19     { 20         this.id = id; 21     } 22 } 23  24 class holder 25 { 26     int index = 0; 27     mantou m[] = new mantou[6]; 28     synchronized void push() 29     { 30         if(index == 5) 31         { 32             try 33             { 34                 this.wait(); 35             } 36             catch(InterruptedException e) 37             { 38                  39             } 40         } 41         m[index] = new mantou(index++); 42         this.notify(); 43     } 44      45     synchronized mantou pop() 46     { 47         if(index == 0) 48         { 49             try 50             { 51                 this.wait();                    // 52             } 53             catch(InterruptedException e) 54             { 55                  56             } 57         } 58         this.notify();                                     // 59         index--; 60         return m[index]; 61     } 62 } 63  64 class shifu implements Runnable 65 { 66     holder ho = null; 67     shifu(holder h) 68     { 69         ho = h; 70     } 71     public void run() 72     { 73         for(int i = 0; i < 20; i++) 74         { 75             ho.push(); 76             System.out.println("生产了:" + i); 77             try 78             { 79                 Thread.sleep((int)(Math.random() * 1000)); 80             } 81             catch(InterruptedException e) 82             { 83                  84             } 85         } 86     } 87 } 88  89 class man implements Runnable 90 { 91     holder ho = null; 92     man(holder h) 93     { 94         ho = h; 95     } 96     public void run() 97     { 98         for(int i = 0; i < 20; i++) 99         {100             ho.pop();101             System.out.println("消费了:" + i);102             try103             {104                 Thread.sleep((int)(Math.random() * 1000));            //105             }106             catch(InterruptedException e)107             {108                 109             }110         }111     }112 }

主要就是wait和notify的使用

2014/9/28消费生产