In the Java language, ++i and i++ operations are not thread-safe and, when used, will inevitably use the Synchronized keyword. The Atomicinteger is a thread-safe plus-minus operation interface.
Unlocked Integer + +, executed several times, the resulting value is mostly less than 200000, but this is the result we do not want to get
classMyThread implements Runnable {Static volatile Longi =0; Public voidrun () { for(intm =0; M <100000; m++) {i++; } }}; Public classTestatomicinteger { Public Static voidMain (string[] args) throws Interruptedexception {MyThread Mt=NewMyThread (); Thread T1=NewThread (MT); Thread T2=NewThread (MT); T1.start (); T2.start (); Thread.Sleep ( -); System. out. println (MYTHREAD.I); }}
You can use Atomicinteger to do this without synchronized.
classMyThread implements Runnable {//static int i = 0; StaticAtomicinteger ai =NewAtomicinteger (0); Public voidrun () { for(intm =0; M <1000000; m++) {ai.getandincrement (); } }}; Public classTestatomicinteger { Public Static voidMain (string[] args) throws Interruptedexception {MyThread Mt=NewMyThread (); Thread T1=NewThread (MT); Thread T2=NewThread (MT); T1.start (); T2.start (); Thread.Sleep ( -); System. out. println (Mythread.ai.Get()); }}
You can see that the results are all 2000000, which means that Atomicinteger is thread safe.
Atomicinteger Source Section Explained
Public classAtomicinteger extends number implements Java.io.Serializable {Private StaticFinalLongSerialversionuid =6214790243416807050L; //setup to use Unsafe.compareandswapint for updates Private StaticFinal Unsafeunsafe=Unsafe.getunsafe (); Private StaticFinalLongValueoffset; Static { Try{Valueoffset=unsafe. Objectfieldoffset (Atomicinteger.class. Getdeclaredfield ("value")); } Catch(Exception ex) {Throw NewError (ex);} } Private volatile intValue
The above is part of the source code in the Atomicinteger, here is the value here, where value uses the volatile keyword, volatile here can be done to enable multiple threads to share variables, However, the problem is that using volatile will make VM optimizations ineffective and inefficient, so use them when necessary, so the Atomicinteger class is not intended to be used in a usage scenario.
The use of Atomicinteger in Java