导航

线程同步-生产者消费者问题

Posted on 2013-04-14 20:38  ChanHuman  阅读(194)  评论(0编辑  收藏  举报
 1 public class ProducerConsumer{
 2     public static void main(String[] args){
 3         WtStack st = new WtStack();
 4         Producer a = new Producer(st);
 5         Consumer b = new Consumer(st);
 6         new Thread(a).start();
 7         new Thread(b).start();
 8     }
 9 }
10 
11 class WoTou {
12     int id;
13     WoTou(int id){
14         this.id=id;
15     }
16     public String toString(){
17         return "WoTou: "+id;
18     }
19 }
20 
21 class WtStack {
22     int index=0;
23     WoTou[] wtarr = new WoTou[10];
24     
25     public synchronized void push(WoTou wt){
26         while(index==wtarr.length){
27             try{
28                 this.wait();
29             }catch(InterruptedException e){
30                 e.printStackTrace();
31             }
32         }
33         this.notify();
34         wtarr[index]= wt;
35         index++;    
36     }
37     
38     public synchronized WoTou pop(){
39         while(index==0){
40             try{
41                 this.wait();
42             }catch(InterruptedException e){
43                 e.printStackTrace();
44             }
45         }
46         this.notify();
47         index--;
48         return wtarr[index];
49     }
50 }
51 
52 class Producer implements Runnable {
53     WtStack st = null;
54     Producer(WtStack a){
55         this.st = a;
56     }
57     public void run(){
58         for(int i=0;i<20;i++){
59             WoTou wt = new WoTou(i);
60             st.push(wt);
61             System.out.println("生产了:"+wt);
62         }
63         try{
64             Thread.sleep(1000);
65         }catch(InterruptedException e){
66             e.printStackTrace();
67         }
68     }
69 }
70 
71 class Consumer implements Runnable {
72     WtStack st = null;
73     Consumer(WtStack a){
74         this.st = a; 
75     }
76     public void run(){
77         for(int i=0;i<20;i++){
78             System.out.println(st.pop());
79         }
80         try{
81             Thread.sleep(1000);
82         }catch(InterruptedException e){
83             e.printStackTrace();
84         }
85     }
86 }