1 public class ProducerConsumer {
2 public static void main(String[] args) {
3 SyncStack ss = new SyncStack();
4 Producer p = new Producer(ss);
5 Consumer c = new Consumer(ss);
6 new Thread(p).start();
7 new Thread(p).start();
8 new Thread(p).start();
9 new Thread(c).start();
10 }
11 }
12
13 class WoTou {
14 int id;
15 WoTou(int id) {
16 this.id = id;
17 }
18 public String toString() {
19 return "WoTou : " + id;
20 }
21 }
22
23 class SyncStack {
24 int index = 0;
25 WoTou[] arrWT = new WoTou[6];
26
27 public synchronized void push(WoTou wt) {
28 while(index == arrWT.length) {
29 try {
30 this.wait();
31 } catch (InterruptedException e) {
32 e.printStackTrace();
33 }
34 }
35 this.notifyAll();
36 arrWT[index] = wt;
37 index ++;
38 }
39
40 public synchronized WoTou pop() {
41 while(index == 0) {
42 try {
43 this.wait();
44 } catch (InterruptedException e) {
45 e.printStackTrace();
46 }
47 }
48 this.notifyAll();
49 index--;
50 return arrWT[index];
51 }
52 }
53
54 class Producer implements Runnable {
55 SyncStack ss = null;
56 Producer(SyncStack ss) {
57 this.ss = ss;
58 }
59
60 public void run() {
61 for(int i=0; i<20; i++) {
62 WoTou wt = new WoTou(i);
63 ss.push(wt);
64 System.out.println("生产了:" + wt);
65 try {
66 Thread.sleep((int)(Math.random() * 200));
67 } catch (InterruptedException e) {
68 e.printStackTrace();
69 }
70 }
71 }
72 }
73
74 class Consumer implements Runnable {
75 SyncStack ss = null;
76 Consumer(SyncStack ss) {
77 this.ss = ss;
78 }
79
80 public void run() {
81 for(int i=0; i<20; i++) {
82 WoTou wt = ss.pop();
83 System.out.println("消费了: " + wt);
84 try {
85 Thread.sleep((int)(Math.random() * 1000));
86 } catch (InterruptedException e) {
87 e.printStackTrace();
88 }
89 }
90 }
91 }