After Java5, we are exposed to the thread atomic operation, that is, in the modification we only need to ensure that the moment is safe, after the corresponding packaging can then process the object of concurrent modification, this article summarizes the atomic series of the use of the class, which contains:
| type |
Integer |
Long |
|
| Basic type |
Atomicinteger |
Atomiclong |
Atomicboolean |
| Array type |
Atomicintegerarray |
Atomiclongarray |
Atomicreferencearray |
| Attribute Atomic modifier |
Atomicintegerfieldupdater |
Atomiclongfieldupdater |
Atomicreferencefieldupdater |
First look at the use of Atomicinteger, Atomicinteger is mainly for integer modification, look at the sample code:
Public class atomicintegerdemo { /** * Common Methods list *@seeAtomicinteger#get () Direct return value *@seeAtomicinteger#getandadd (int) Adds the specified data, returning the data before the change *@seeAtomicinteger#getanddecrement () reduced by 1, returning data before reduction *@seeAtomicinteger#getandincrement () increased by 1 to return the data before the increase *@seeAtomicinteger#getandset (int) Sets the specified data, returning the data before the setting * *@seeAtomicinteger#addandget (int) Returns the added data after adding the specified data *@seeAtomicinteger#decrementandget () decrease by 1, return the reduced value *@seeAtomicinteger#incrementandget () Adds 1, returns the added value *@seeAtomicinteger#lazyset (int) is set only when get@seeAtomicinteger#compareandset (int, int) tries to add a new contrast and returns true if the increase succeeds otherwise false */ Public Final StaticAtomicinteger Test_integer =NewAtomicinteger (1); Public Static void Main(String []args) { for(inti =0; I <Ten; i++) {//Open 10 threads NewThread () { Public void Run() {Try{Thread.Sleep ( +); }Catch(Interruptedexception e) {E.printstacktrace (); }intnow = Test_integer.incrementandget ();//self-incrementSystem.out.println (Thread.CurrentThread (). GetName () +"Get Value:"+ now); }}.start (); } }}
Look at the results:
Thread-3 Get Value:4
Thread-7 Get Value:5
Thread-9 Get Value:9
Thread-4 Get Value:6
Thread-0 Get Value:3
Thread-1 Get Value:8
Thread-5 Get Value:11
Thread-8 Get Value:7
Thread-2 Get Value:10
Thread-6 Get Value:2
As you can see, 10 threads are thread-safe and there is no conflict. That is, we use the atomic Operation class to operate the basic type int can solve the thread security problem, a thread in the operation, the other threads will be excluded, we do not have to manually use the synchronized to achieve mutual exclusion. Atomiclong and Atomicboolean are similar, they do not give examples.
The following is to begin to say atomic array usage, atomic array requirements are not allowed to modify the length, and so on, not as rich as the collection class operation, but it can make the array of each element of the operation is absolutely safe, that is, its refinement of the force or to the elements on the array, did two times packaging, although the array type, But in the end it is the number of operations in the array, so the basic type of the above, the array type is also well understood. Here is the main look at the use of Atomicintegerarray, other similar.
Public class atomicintegerarraytest { /** * Common Methods list *@seeAtomicintegerarray#addandget (int, int) performs the addition, the first parameter is the subscript for the array, the second argument is the increased quantity, and the result of the increment is returned *@seeAtomicintegerarray#compareandset (int, int, int) contrast modified, parameter 1: array subscript, Parameter 2: Original value, parameter 3, modify target value, modify successful return true otherwise false *@seeThe atomicintegerarray#decrementandget (int) parameter is an array subscript that reduces the corresponding number of arrays by 1, returning the reduced data *@seeThe atomicintegerarray#incrementandget (int) parameter is an array subscript that increments the corresponding number of arrays by 1, returning the added data *@seeAtomicintegerarray#getandadd (int, int) and addandget are similar, except that the return value is the data before the change *@seeatomicintegerarray#getanddecrement (int) is similar to Decrementandget, except that the data before the change is returned *@seeatomicintegerarray#getandincrement (int) is similar to Incrementandget, except that the data before the change is returned *@seeAtomicintegerarray#getandset (int, int) sets the number of the corresponding subscript to the specified value, the second parameter is the set value, and the data before the change is returned. Private Final StaticAtomicintegerarray Atomic_integer_array =NewAtomicintegerarray (New int[]{1,2,3,4,5,6,7,8,9,Ten}); Public Static void Main(String []args)throwsinterruptedexception {Thread []threads =Newthread[Ten]; for(inti =0; I <Ten; i++) {Final intindex = i;Final intThreadnum = i; Threads[i] =NewThread () { Public void Run() {intresult = Atomic_integer_array.addandget (index, Index +1); System.out.println ("Thread number is:"+ Threadnum +", the corresponding original value is:"+ (Index +1) +", the result of the increase is:"+ result); } }; Threads[i].start (); } for(Thread thread:threads) {Thread.Join (); } System.out.println ("=========================>\n execution has completed, results list:"); for(inti =0; I < atomic_integer_array.length (); i++) {System.out.println (Atomic_integer_array.get (i)); } }}
The result of the run is that each array element is given the same value, and they do not affect each other.
| 3. Use as a class attribute |
When a data type is a property in a class, and then we want to manipulate the data, we need to use the attribute atomic modifier, here is the example of an integer, namely: Atomicintegerfieldupdater. The sample code is as follows:
Public class atomicintegerfieldupdatertest { StaticClass A {volatile intIntvalue = -; }/** * can directly access the corresponding variable, to modify and process the * condition: to be in an accessible area, if it is private or satchel access to the default type and non-Father class protected cannot access the * second access to the object cannot be a static type Variable (because it cannot be computed at the time the offset of the property is computed), nor can it be a variable of the final type (because it cannot be modified at all), it must be a normal member variable * * Method (the Atomicinteger is almost identical on the description, and the only difference is that the first parameter requires a reference to the object passed in) *@seeAtomicintegerfieldupdater#addandget (Object, int) *@seeAtomicintegerfieldupdater#compareandset (Object, int, int) *@seeAtomicintegerfieldupdater#decrementandget (Object) *@seeAtomicintegerfieldupdater#incrementandget (Object) * *@seeAtomicintegerfieldupdater#getandadd (Object, int) *@seeAtomicintegerfieldupdater#getanddecrement (Object) *@seeAtomicintegerfieldupdater#getandincrement (Object) *@seeAtomicintegerfieldupdater#getandset (Object, int) */ Public Final Staticatomicintegerfieldupdater<a> atomic_integer_updater = Atomicintegerfieldupdater.newupdater (A.class,"Intvalue"); Public Static void Main(String []args) {FinalA A =NewA (); for(inti =0; I <Ten; i++) {NewThread () { Public void Run() {if(Atomic_integer_updater.compareandset (A, -, -) {System.out.println (Thread.CurrentThread (). GetName () +"The corresponding value has been modified!" "); }}}.start (); } } }
As you can see, the class and class attributes need to be passed in before they are passed in actually with the previous operation of the integer is no different, the essence is the same, run a bit, results only one thread can modify it.
The use of the atomic operation class of the thread is simply summed up here, the other operating class principles are similar, you can refer to the JDK's documentation, it is easy to write the corresponding test code.
Related reading: http://blog.csdn.net/column/details/bingfa.html
-Willing to share and progress together!
-More articles please see: http://blog.csdn.net/eson_15
Use of the "Java Concurrency" Atomic Operation class