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