Java Reference
In-Depth Information
In this particular case, we can add the keyword
synchronized
to either the method
or around the specific code. If we add
synchronized
to the
increment()
method in
the
Counter
class, then it looks like this:
public synchronized void
increment()
{
int
local;
local = counter;
local++;
counter = local;
}
If we add
synchronized
inside the code, then we can write
public void
increment()
{
int
local;
synchronized
(
this
)
{
local = counter;
local++;
counter = local;
}
}
Either version will result in a counter whose final value is always 30,000. There are
many other issues involved in thread management, concurrency, and synchronization.
These concepts are often covered in more detail in an operating systems or parallel
programming course.
Self-Test Exercises
3. In the
run()
method of Display 19.5, make the thread sleep a random amount
of time between one and fi ve milliseconds. You should see an increase in the
number of problems caused by race conditions. Can you explain why?
4. Here is some code that synchronizes thread access to a shared variable. How
come it is not guaranteed to output 30,000 every time it is run?
public class
Counter
{
private int
counter;
public
Counter()
{
counter = 0;
}