[Java multithreading] correct use of volatile keywords, multi-thread volatile

Source: Internet
Author: User

[Java multithreading] correct use of volatile keywords, multi-thread volatile

The volatile variable hassynchronizedBut not Atomic. In a multi-threaded environment, variables using the volatile keyword can only read the latest modified variable values when reading variables from different threads, however, when modifying the variable value, thread security cannot be ensured (there may be a write value overwrite phenomenon ). The following test code shows how to use the volatile keyword.

 

1/*** <B> correct volatile keyword usage </B> <br> 3 * @ author Gaylen 4 * @ version V1.1.0 5 * history 6*1.1.0, gaylen FE 7 * @ since Java 6.0 8 */9 public class TestVolatile {10 11/** volatile + atomic ensure read/write security */12 public static volatile AtomicInteger count1 = new AtomicInteger (0 ); 13 14/** volatile implements read Security, but cannot guarantee write security */15 public static volatile int count2 = 0; 16 17/** volatile + synchronized achieves read and write security */18 public static volatile int count3 = 0; 19 20/** static only ensures global uniqueness, but cannot guarantee read/write security */21 public static int count4 = 0; 22 23 public static synchronized void count3Increment () {24 TestVolatile. count3 ++; 25} 26 27/** Number of test threads */28 public static final int numOfThread = 1000; 29 30/** thread helper class, ensure that all threads are completed */31 private static CountDownLatch countDownLatch = new CountDownLatch (numOfThread); 32 33 public static void increment () {34 try {35 Thread. sleep (1); 36} catch (InterruptedException e) {37} 38 count1.getAndIncrement (); 39 count2 ++; 40 count3Increment (); 41 count4 ++; 42} 43 44/** 45 * output result 46 * wait until all threads have completed execution, output result 47 */48 public static void print () {49 try {50 countDownLatch. await (); 51} catch (InterruptedException e) {52 e. printStackTrace (); 53} 54 System. out. println ("running result: count1 =" + TestVolatile. count1.get (); 55 System. out. println ("running result: count2 =" + TestVolatile. count2); 56 System. out. println ("running result: count3 =" + TestVolatile. count3); 57 System. out. println ("running result: count4 =" + TestVolatile. count4); 58 System. out. println ("-----------------------------------"); 59 60} 61 62/** 63 * <B> program entry </B> <br> 64 * starts 1000 threads at the same time, add 65 * @ param args66 */67 public static void main (String [] args) {68 for (int I = 0; I <numOfThread; I ++) {69 new Thread (new Runnable () {70 71 @ Override72 public void run () {73 for (int index = 0; index <1000; index ++) {74 TestVolatile. increment (); 75} 76 countDownLatch. countDown (); 77} 78 }). start (); 79} 80 print (); 81} 82}

The output result of the test program is as follows:

Running result: count1 = 1000000
Running result: count2 = 998528
Run the following command: count3 = 1000000
Run the following command: count4 = 999892
---------------------------------------

The test program shows that using volatile + synchronized or volatile + atomic variable can simultaneously ensure secure variable read/write in multi-threaded environments.

 

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.