1
2
3
4
5
6
7
8class Resource {
9
10
11 public
12 boolean empty = true;
13
14 public
15 int i,j;
16
17 public
18 Resource() {
19 i = 0;
20 j = 0;
21 }
22}
23
24
25
26public
27class SyncTest {
28
29
30
31
32
33
34 public static
35 Resource buffer = new Resource();
36
37
38
39
40 public static
41 void main(String[] argv) {
42 Thread producer =
43 new Producer(buffer);
44
45 Thread consumer =
46 new Consumer(buffer);
47
48 producer.setName("producer");
49 consumer.setName("consumer");
50
51 producer.start();
52 consumer.start();
53 }
54}
55
56
57
58abstract
59class SleepyThread extends Thread {
60
61 public
62 void sleepAWhile() {
63 try {
64 sleep( (int)(Math.random() * 500) );
65 }
66 catch ( InterruptedException e ) { }
67 }
68
69
70
71 public
72 abstract
73 void doIt();
74
75
76
77 public
78 void run() {
79 System.out.println(getName() + " started");
80
81 for (int i = 0;
82 i < 10;
83 ++ i ) {
84 doIt();
85 sleepAWhile();
86 }
87
88 System.out.println(getName() + " finished");
89 }
90}
91
92
93
94class Producer extends SleepyThread {
95
96
97 private
98 Resource buffer;
99
100 public Producer(Resource buffer) {
101 super();
102 this.buffer = buffer;
103 }
104
105
106
107 public
108 void doIt() {
109 synchronized ( buffer ) {
110
111 while ( ! buffer.empty ) {
112
113 try {
114 System.out.println(getName() + " waiting");
115 buffer.wait();
116 }
117 catch ( InterruptedException e ) { }
118 System.out.println(getName() + " notified");
119 }
120
121 System.out.println(getName() + " incrementing i");
122
123 ++ buffer.i;
124
125
126 sleepAWhile();
127
128 System.out.println(getName() + " incrementing j");
129
130 ++ buffer.j;
131
132 buffer.empty = false;
133
134 buffer.notify();
135 }
136 }
137}
138
139
140
141class Consumer extends SleepyThread {
142
143
144 private
145 Resource buffer;
146
147 public Consumer(Resource buffer) {
148 super();
149 this.buffer = buffer;
150 }
151
152
153
154 public
155 void doIt() {
156 synchronized ( buffer ) {
157 int i,j;
158
159 while ( buffer.empty ) {
160
161 try {
162 System.out.println(getName() + " waiting");
163 buffer.wait();
164 }
165 catch ( InterruptedException e ) { }
166 System.out.println(getName() + " notified");
167 }
168
169 System.out.println(getName() + " reading i");
170
171 i = buffer.i;
172
173
174 sleepAWhile();
175
176 System.out.println(getName() + " reading j");
177
178 j = buffer.j;
179
180 System.out.println(getName() + " i,j = " + i + "," + j);
181
182 buffer.empty = true;
183
184 buffer.notify();
185 }
186 }
187}