System.out.println(name + " got: " +
Shared.ai.getAndSet(i));
}
}
In the program, a staticAtomicIntegernamedaiis created byShared. Then, three threads
of typeAtomThreadare created. Insiderun( ),Shared.aiis modified by callinggetAndSet( ).
This method returns the previous value and then sets the value to the one passed as an
argument. The use ofAtomicIntegerprevents two threads from writing toaiat the same time.
In general, the atomic operations offer a convenient (and possibly more efficient) alternative
to the other synchronization mechanisms when only a single variable is involved.
The Concurrency Utilities Versus Java’s Traditional Approach
Given the power and flexibility found in the new concurrency utilities, it is natural to ask
the following question: Do they replace Java’s traditional approach to multithreading and
synchronization? The answer is a resounding no! The original support for multithreading
and the built-in synchronization features are still the mechanism that should be employed
for many, many Java programs, applets, and servlets. For example,synchronized,wait( ),
andnotify( )offer elegant solutions to a wide range of problems. However, when extra
control is needed, the concurrency utilities are now available to handle the chore.
812 Part II: The Java Library