Atomicinteger with jdk5.0, it is located under the Java.util.concurrent.atomic package,Atomicinteger, an integer class that provides atomic manipulation. In other words, in the Java language, ++i and i++ operations are not thread-safe, and when used, the Synchronized keyword is unavoidable. Atomicinteger uses a thread-safe addition and subtraction interface, which means that when multiple threads operate on the same variable, using Atomicinteger does not cause the variable to be problematic and is more efficient than using synchronized, and now looks at an example:
Package Cn.kge.com;import Java.util.concurrent.atomic.atomicinteger;public class Atomicdemo {public final static Atomicinteger Atomicinteger = new Atomicinteger (1); public static void Main (string[] args) throws interruptedexception {final Thread []threads = new THREAD[10]; for (int i = 0; i < ten; i++) {final int num = i; Threads[i] = new Thread () {public void run () {try {Thr Ead.sleep (1000); } catch (Interruptedexception e) {e.printstacktrace (); } int now = Atomicinteger.incrementandget (); System.out.println ("I am Thread:" + num + ", I get the value up, the added value is:" + now); } }; Threads[i].start (); } for (Thread t:threads) {t.join (); } System.out.println ("Final run Result:" + atomicinteger.get ()); }}
The operating result is:
I am a thread: 1, I get the value, the increment value is: 2
I am a thread: 2, I get the value, the increment value is: 3
I am a thread: 0, I get the value, the increment value is: 4
I am a thread: 9, I get the value, the increment value is: 5
I am a thread: 5, I get the value, the increment value is: 6
I am a thread: 4, I get the value, the increment value is: 7
I am a thread: 8, I get the value, the increment value is: 8
I am a thread: 3, I get the value, the increment value is: 9
I am a thread: 7, I get the value, the increment value is: 10
I am a thread: 6, I get the value, the increment value is: 11
Final Run Result: 11
Why would it be 11? Because the initialization in his constructor is 1, then there are 10 threads, each thread adds 1, or 11, which is when a single thread executes, Atomicinteger plus 1 does not have a problem.
Atomicinteger use note where you create a Atomicinteger object as a member variable, and do not use this object in the local area!
Android multi-threaded access integer problem, please use Atomicinteger