Java Reference
In-Depth Information
Display 19.5
The RaceConditionTest Class (part 2 of 2)
8 public void run()
9 {
10 countObject.increment();
11 }
Invokes the code in Display 19.4
where the race condition occurs.
12 public static void main(String[] args)
13 {
14 int i;
15 Counter masterCounter = new Counter();
16 RaceConditionTest[] threads = new RaceConditionTest[30000];
The single instance of the Counter object.
Array of 30,000 threads.
17 System.out.println("The counter is " + masterCounter.value());
18 for (i = 0; i < threads.length; i++)
19 {
20 threads[i] = new RaceConditionTest(masterCounter);
21 threads[i].start();
22 }
Give each thread a reference to
the single Counter object and
start each thread.
23 // Wait for the threads to finish
24 for (i = 0; i < threads.length; i++)
25 {
26 try
27 {
28 threads[i].join();
29 }
30 catch (InterruptedException e)
31 {
32 System.out.println(e.getMessage());
33 }
34 }
35 System.out.println("The counter is " + masterCounter.value());
37 }
38 }
Waits for the thread to complete.
Sample Dialogue (output will vary)
The counter is 0
The counter is 29998
So how do we fix this problem? The solution is to make each thread wait so only
one thread can run the code in increment() at a time. This section of code is called
a critical region . Java allows you to add the keyword synchronized around a critical
region to enforce the requirement that only one thread is allowed to execute in this
region at a time. All other threads will wait until the thread inside the region is finished.
critical region
synchronized
 
 
Search WWH ::




Custom Search