Chapter 26: The Concurrency Utilities 811
B: 2
B is sleeping.
B is unlocking count.
java.util.concurrent.locksalso defines theReadWriteLockinterface. This interface
specifies a reentrant lock that maintains separate locks for read and write access. This
enables multiple locks to be granted for readers of a resource as long as the resource is not
being written.ReentrantReadWriteLockprovides an implementation ofReadWriteLock.
Atomic Operations
java.util.concurrent.atomicoffers an alternative to the other synchronization features when
reading or writing the value of some types of variables. This package offers methods that
get, set, or compare the value of a variable in one uninterruptible (that is, atomic) operation.
This means that no lock or other synchronization mechanism is required.
Atomic operations are accomplished through the use of classes, such asAtomicIntegerand
AtomicLong, and methods such asget( ),set( ),compareAndSet( ),decrementAndGet( ),
andgetAndSet( ), whichperform the action indicated by their names.
Here is an example that demonstrates how access to a shared integer can be synchronized
by the use ofAtomicInteger:
// A simple example of Atomic.
import java.util.concurrent.atomic.*;
class AtomicDemo {
public static void main(String args[]) {
new AtomThread("A");
new AtomThread("B");
new AtomThread("C");
}
}
class Shared {
static AtomicInteger ai = new AtomicInteger(0);
}
// A thread of execution that increments count.
class AtomThread implements Runnable {
String name;
AtomThread(String n) {
name = n;
new Thread(this).start();
}
public void run() {
System.out.println("Starting " + name);
for(int i=1; i <= 3; i++)