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 sleepAWhile();
79 }
80
81 System.out.println(getName() + " finished");
82 }
83}
84
85
86
87class Producer extends SleepyThread {
88
89
90 private
91 Resource buffer;
92
93 public Producer(Resource buffer) {
94 super();
95 this.buffer = buffer;
96 }
97
98
99
100 public
101 void doIt() {
102 synchronized ( buffer ) {
103
104 System.out.println(getName() + " incrementing i");
105
106 ++ buffer.i;
107
108
109 sleepAWhile();
110
111 System.out.println(getName() + " incrementing j");
112
113 ++ buffer.j;
114 }
115
116 sleepAWhile();
117 }
118}
119
120
121
122class Consumer extends SleepyThread {
123
124
125 private
126 Resource buffer;
127
128 public Consumer(Resource buffer) {
129 super();
130 this.buffer = buffer;
131 }
132
133
134
135 public
136 void doIt() {
137 synchronized ( buffer ) {
138 int i,j;
139
140 System.out.println(getName() + " reading i");
141
142 i = buffer.i;
143
144
145 sleepAWhile();
146
147 System.out.println(getName() + " reading j");
148
149 j = buffer.j;
150
151 System.out.println(getName() + " i,j = " + i + "," + j);
152 }
153
154 sleepAWhile();
155 }
156}