背过程序-生产者消费者问题

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