Java Reference
In-Depth Information
Display 19.4
The
Counter
Class
1
public class
Counter
2 {
3
private int
counter;
4
public
Counter()
5 {
6 counter = 0;
7 }
8
public int
value()
9 {
10
return
counter;
11 }
12
public void
increment()
13 {
14
int
local;
15 local = counter;
16 local++;
17 counter = local;
18 }
19 }
The only new tool that we need for our demonstration program is a way to wait
for all the threads to finish. If we do not wait, then our program might output the
counter before all the threads have had a chance to increment the value. We can wait
by invoking the
join()
method for every thread we create. This method waits for the
thread to complete. The
join()
method throws
InterruptedException
. This is a
checked exception so we must use the try/catch mechanism.
The class
RaceConditionTest
in Display 19.5 illustrates the race condition. You
may have to run the program several times before you get a value less than 30,000.
Problems as a result of race conditions are often rare occurrences. This makes them
extremely hard to find and debug!
VideoNote
Walkthrough
of a Program
with Race
Conditions
Display 19.5
The
RaceConditionTest
Class
(part 1 of 2)
1
public class
RaceConditionTest
extends
Thread
2 {
3
private
Counter countObject;
Stores a reference to a
single
Counter
object.
4
public
RaceConditionTest(Counter ctr)
5 {
6 countObject = ctr;
7 }