多线程实例01--包子买卖

1.创建一个实体类

 1 package Th05;
 2 
 3 public class Baozi5 {
 4 
 5     int id ;
 6 
 7     Baozi5 (int id){
 8         this.id = id;
 9     }
10     
11     public String toString(){
12         return "包子:" + id;
13     }
14 }

 

2.创建工厂

 1 package Th05;
 2 
 3 public class Factory5 {
 4 
 5     Baozi5[] num = new Baozi5[10];
 6     int index = 0;
 7 
 8     public synchronized void addBaozi(Baozi5 m){
 9 
10         try {
11             while( index == num.length){
12                 System.out.println("_______________生产满咯_____________");
13                 this.wait();
14             }
15             this.notify();
16         }catch (InterruptedException e) {
17             e.printStackTrace();
18         }
19         num[index] = m;
20         index++;
21         System.out.println("生产了"+ m + "共" + index + "个包子");
22     }
23     
24     public synchronized Baozi5 popBaozi(){
25         try{
26             while(index == 0) {
27                 System.out.println("_____________卖光咯_____________");
28                 this.wait();
29             }
30             this.notify();
31         }catch(Exception e){
32             e.printStackTrace();
33         }
34         index--;
35         System.out.println("消费了"+ num[index] +"共"+ index +"个包子");
36         return num[index];
37     }
38 
39     
40 }

 

3.买包子

 1 package Th05;
 2 
 3 public class Procuder5 implements Runnable{
 4 
 5     Factory5 fa = new Factory5();
 6     
 7     Procuder5 (Factory5 fa){
 8         this.fa = fa;
 9     }
10 
11     public void run() {
12         for(int i=0; i<10; i++){
13             Baozi5 b = new Baozi5(i);
14             fa.addBaozi(b);
15             try {
16                 Thread.sleep((int) (Math.random() * 500));
17             } catch (InterruptedException e) {
18                 e.printStackTrace();
19             }
20         }
21         
22     }
23     
24     
25 }

 

4.卖包子

 1 package Th05;
 2 
 3 public class Customer5 implements Runnable{
 4 
 5     Factory5 fa = new Factory5();
 6     
 7     Customer5(Factory5 fa){
 8         this.fa = fa;
 9     }
10 
11     public void run() {
12         for(int i=0; i<20; i++){
13             Baozi5 b = fa.popBaozi();
14             
15             try {
16                 Thread.sleep((int) (Math.random() * 1000));
17             } catch (InterruptedException e) {
18                 e.printStackTrace();
19             }
20         }
21     }
22 
23 
24 }

 

5.测试

 1 package Th05;
 2 
 3 public class Test {
 4 
 5     public static void main(String[] args){
 6         Factory5 f = new Factory5();
 7         Procuder5 p = new Procuder5(f);
 8         Customer5 c = new Customer5(f);
 9         
10         Thread t1 = new Thread(p);
11         Thread t2 = new Thread(c);
12 
13         t1.start();
14         t2.start();
15     }
16 }

 

posted @ 2015-01-07 17:23  江湖一笑  阅读(341)  评论(0编辑  收藏  举报