Java thread-volatile does not guarantee atomicity

Source: Internet
Author: User

The following is an example of a total atomicity implementation by using volatile:

The final result of the variable number is calculated by creating 100 threads.

 Packagecom. sychronized; Public classVolatiledemo {Private volatileintNumber=0;  Public intGetNumber () {return  This. number; }     Public voidIncrease () { This. number++; }     Public Static voidMain (string[] args) {//TODO auto-generated Method Stub        FinalVolatiledemo voldemo=NewVolatiledemo ();  for(inti=0;i<100;i++)        {            New Thread (new Runnable () {@Override public void Run () {voldemo.increase ();        }}). Start (); }                //If there are child threads running, the main thread will let the CPU resources//The main thread continues to execute until all the child threads have run out         while(Thread.activecount () >1) {Thread.yield (); } System.out.println ("Number:" +Voldemo.getnumber ()); }}

Operation Result:

Several results were found:

The reason for this result is that the volatile keyword has visibility, and number++ actually has three steps, but not atomicity.

Java thread-volatile does not guarantee atomicity

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.