The java.util.concurrent.atomic provides classes on atomic operations, including: Atomiclong, Atomicinteger, Atomicboolean. And the Atomicintegerarray, Atomiclongarray of the array operation.
The initial understanding of the thread is DEMO2 because of the security issues caused by atomic operations. The use of Atomicinteger can be solved.
Public classDemo2 {PrivateAtomicinteger value =NewAtomicinteger (1); Public intGetNext () {//value is added 1, and then returned, the entire operation as an atom. returnvalue.getandincrement (); } Public Static voidMain (string[] args) {FinalDemo2 demo =NewDemo2 (); Runnable R=NewRunnable () {@Override Public voidrun () {System.out.println (Demo.getnext ()); } }; for(inti = 0; I <500;i++){ NewThread (R). Start (); } }}
Atomicinteger Method of Construction:
Atomicinteger () creates a new Atomicinteger with an initial value of 0.
Atomicinteger (int initialvalue) creates a new atomicinteger with the given initial value.
Common methods
int get () gets the current value.
int getanddecrement () atomically subtract the current value by 1.
int getandincrement () atomically adds the current value to 1.
int Incrementandget () atomically adds the current value to 1.
int Decrementandget () atomically subtract the current value by 1.
int addandget (int delta) atomically adds the given value to the current value.
int getandadd (int delta) atomically adds the given value to the current value.
Note: The difference between getandxxx and Xxxandget reference: + + I and i++.
The usage of Atomiclong, Atomicinteger, Atomicboolean is similar.
The following is an example of Atomicintegerarray, similar to Atomiclongarray's usage.
Public classAtomicintegerarraytest { Public Static voidMain (string[] args) {int[] A = {}; //creates a Atomicintegerarray object from a given array, and all of the following operations are actually manipulating the array with an atomic operation. Atomicintegerarray ala =NewAtomicintegerarray (a); //adds 1 to the No. 0 element and returns a valueSystem.out.println (Ala.incrementandget (0)); //adds 4 to the 1th element and returns a valueSystem.out.println (Ala.addandget (1, 4)); //minus 1 for the 2nd element, and returns a valueSystem.out.println (Ala.decrementandget (2)); //minus 2 for the 1th element, and returns a valueSystem.out.println (Ala.addandget (1, 2)); }}
Third, atomic