J2SE 5.0 provides a set of atomic classes to help us simplify the synchronization process. The basic working principle is to use the synchronous synchronized method to implement a long, Integer, object increment, Decrement, assignment (update) operation. For example, the + + operator Atomicinteger can increment the integer that it holds atomic. Program code that requires access to two or more atomic variables (or two or more operations on a single atomic variable) usually needs to be synchronize so that both operations can be treated as a atomic unit.
Java Multithreading Usage-use Atomicinteger to see the powerful features of Atomicinteger with a simple comparison of two examples
Class Counter { private volatile int count = 0; public synchronized void increment () { count++; To perform a thread-safe execution of count++, you need to lock the public int GetCount () { return count; }}
Class Counter { private Atomicinteger count = new Atomicinteger (); public void Increment () { count.incrementandget (); } After you use Atomicinteger, you do not need to lock, or you can implement thread safety. public int GetCount () { return count.get (); }}
From the example above we can see that the use of Atomicinteger is very safeSo why not use the register to add, such as count++, because this count is thread insecure, high concurrency access statistics will be wrong, and atomicinteger why can achieve more than chaos, handle high concurrency to cope with it? This is implemented by the hardware-supplied atomic operation instructions. In the case of non-intense competition, the overhead is smaller and faster. The atomic operations classes implemented in Java.util.concurrent include: Atomicboolean, Atomicinteger, Atomiclong, Atomicreference.
[Android Pro] The use of Atomicinteger