java.util.concurrent.atomic
can get, set, or compare the value of a variable in one uninterruptible operation.
No lock or other synchronization mechanism is required.
The following code shows how to access a shared integer via AtomicInteger :
// A simple example of Atomic. import java.util.concurrent.atomic.AtomicInteger; public class Main { public static void main(String args[]) { new AtomThread("A"); new AtomThread("B"); new AtomThread("C"); }//w w w. j a v a2 s . co m } 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++) System.out.println(name + " got: " + Shared.ai.getAndSet(i)); } }