The principle and practice of Java Concurrent Programming 13: The principle and use of the atomic class provided by JDK

Source: Internet
Author: User
Tags cas

Atomic Update Basic Type

Atomic Update Array

Atomic Update abstract Type

Atomic Update Field

Atomic Update Basic type:

Package com.roocon.thread.t8;

Import Java.util.concurrent.atomic.AtomicInteger;
Import Java.util.concurrent.atomic.AtomicIntegerArray;

public class Sequence {
Private Atomicinteger value = new Atomicinteger (0);
private int [] s = {2,1,4,6};
Atomicintegerarray a = new Atomicintegerarray (s);

public int GetNext () {
A.getandincrement (2);//give the element labeled 2 plus 1
A.getandadd (2, 10);//Get the element labeled 2 and add 10
for (int i=0; i < a.length (); i++) {
System.out.println (A.get (i));
}
return Value.getandincrement ();
}

public static void Main (string[] args) {
Sequence Sequence = new Sequence ();
New Thread (New Runnable () {
@Override
public void Run () {
while (true) {
System.out.println (Thread.CurrentThread (). GetName () + "" +sequence.getnext ());
try {
Thread.Sleep (100);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
}). Start ();
New Thread (New Runnable () {
@Override
public void Run () {
while (true) {
System.out.println (Thread.CurrentThread (). GetName () + "" +sequence.getnext ());
try {
Thread.Sleep (100);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
}). Start ();
New Thread (New Runnable () {
@Override
public void Run () {
while (true) {
System.out.println (Thread.CurrentThread (). GetName () + "" +sequence.getnext ());
try {
Thread.Sleep (100);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
}). Start ();
}
}

Operation Result:

Thread-0 0thread-1 1thread-2 2thread-0 3thread-1 4thread-2 5 ...
Package Com.roocon.thread.t8;import Java.util.concurrent.atomic.atomicinteger;import Java.util.concurrent.atomic.atomicintegerarray;import Java.util.concurrent.atomic.AtomicIntegerFieldUpdater; Import Java.util.concurrent.atomic.atomicreference;public class Sequence {private Atomicinteger value = new Atomicinte    GER (0); atomicreference<user> User = new atomicreference<> (); Performs atomic operations on User's set and get atomicintegerfieldupdater<user> old = Atomicintegerfieldupdater.newupdater (User.class,    "Old");        public int GetNext () {User user = new User ();        System.out.println (old.getandincrement (user));        System.out.println (old.getandincrement (user));        System.out.println (old.getandincrement (user));    return Value.getandincrement ();        } public static void Main (string[] args) {Sequence Sequence = new Sequence (); New Thread (New Runnable () {@Override public void run () {System.out.println (Threa D.cUrrentthread (). GetName () + "" +sequence.getnext ());                   try {thread.sleep (100);                   } catch (Interruptedexception e) {e.printstacktrace ();    }}). Start (); }}

Operation Result:

012thread-0 0

Understanding of CAs Source code:--Preliminary understanding

In the Atomicinteger, there is a source code:

Public final int getandupdate (Intunaryoperator updatefunction) {        int prev, next;        do {            prev = get ();            Next = Updatefunction.applyasint (prev);        } while (!compareandset (prev, next));        return prev;    }

Public final Boolean compareandset (int expect, int update) {
Return Unsafe.compareandswapint (this, valueoffset, expect, update);
}

Among them, Compareandswap is the abbreviation of CAs. Returns True if Prev and next are not equal. Otherwise, returns false. Finally, it is done through unsafe.

The code above indicates that if Compareandset returns True, the while condition is false, exiting the loop and returning the Prev value. If Compareandset returns false, then while is true, the loop body is resumed, the value of Prev is retrieved again, and the updated value is retrieved until the Compareandset value returned is true.

The following steps are outlined in the demo source:

// 1        Next = prev + 1;         boolean flag = CAs (prev, next);         if (flag) {            return  prev;        } Else {            1        } Object Pre

Resources:

"Java concurrent programming and combat" dragon Fruit College

The principle and practice of Java Concurrent Programming 13: The principle and use of the atomic class provided by JDK

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.