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