[Java multithreading] volatile keyword correct use method

Source: Internet
Author: User

Volatile variables have synchronized the visibility characteristics, but do not have atomic characteristics, that is, in a multithreaded environment, variables using the volatile keyword can only ensure that different threads read variables, you can read the latest modified variable value, but modify the value of the variable, but there is no guarantee of thread safety ( There may be write-value overrides). The following test code shows a few ways to use the volatile keyword.

1 /**2 * <b>volatile keyword correct usage </b><br>3  * @authorGaylen4  * @versionV1.1.05 * History6 * 1.1.0, November 20, 2014 Gaylen FE7  * @sinceJava 6.08  */9  Public classTestvolatile {Ten  One     /**volatile + atomic guarantees read and write security*/ A      Public Static volatileAtomicinteger count1 =NewAtomicinteger (0); -  -     /**volatile for read security, but no guarantee of write security*/ the      Public Static volatile intCount2 = 0; -  -     /**volatile + synchronized for read and write security*/ -      Public Static volatile intCount3 = 0; +  -     /**static only guarantees global uniqueness, but does not guarantee read and write security*/ +      Public Static intCOUNT4 = 0; A  at      Public Static synchronized voidcount3increment () { -testvolatile.count3++; -     } -  -     /**number of test threads*/ -      Public Static Final intNumofthread = 1000; in  -     /**thread helper class to ensure all threads are executed*/ to     Private StaticCountdownlatch Countdownlatch =NewCountdownlatch (numofthread); +  -      Public Static voidincrement () { the         Try { *Thread.Sleep (1); $}Catch(interruptedexception e) {Panax Notoginseng         } - count1.getandincrement (); thecount2++; + count3increment (); Acount4++; the     } +  -     /** $ * Output Results $ * Wait for all threads to finish executing, output result -      */ -      Public Static voidprint () { the         Try { - countdownlatch.await ();Wuyi}Catch(interruptedexception e) { the e.printstacktrace (); -         } WuSYSTEM.OUT.PRINTLN ("Run Result: count1=" +TestVolatile.count1.get ()); -SYSTEM.OUT.PRINTLN ("Run Result: count2=" +testvolatile.count2); AboutSYSTEM.OUT.PRINTLN ("Run Result: count3=" +testvolatile.count3); $SYSTEM.OUT.PRINTLN ("Run Result: count4=" +testvolatile.count4); -System.out.println ("---------------------------------------"); -  -     } A  +     /** the * <b> Program Entry </b><br> - * Start 1000 threads at the same time to increase operation $      * @paramargs the      */ the      Public Static voidMain (string[] args) { the          for(inti = 0; i < Numofthread; i++) { the             NewThread (NewRunnable () { -  in @Override the                  Public voidrun () { the                      for(intindex = 0; Index < 1000; index++) { About testvolatile.increment (); the                     } the Countdownlatch.countdown (); the                 } + }). Start (); -         } the print ();Bayi     } the}

The test program output results are as follows:

Running Result: count1=1000000
Running Result: count2=998528
Running Result: count3=1000000
Running Result: count4=999892
---------------------------------------

The test program shows that using volatile + synchronized or volatile + atom variables can guarantee the safe variable reading and writing in multi-threaded environment.

[Java multithreading] volatile keyword correct use method

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.