In Java , each thread has a piece of its own working memory area, which saves a copy of the public variable value from the main memory. Non - volatile , variable-fit variables are generally independent of the value modifications in each thread. And as shown.
1. Start execution when A,B thread from the main memory area load variable i=0. the value is the same at this time.
2. When the B - thread i=1 The variable, the i=1 is not immediately written to the home area, so A thread workspace i is still equal to 0.
3. If the i variable is modified with Volatile ,theB thread Changes The value of the variable i and returns it back to the main memory area immediately. As shown in.
Package List;public class Test {volatile int i = 0;public void Tryexit () {if (I! = i) {/////When the left I reads memory value, Swapvalue immediately changes the value of I when right I read the memory value, I will find that the value changes,//So the program will appear the value of I can be different on both sides of the result appears. If the value is updated immediately without volatile, it should be executed continuously System.out.println (i + "" + i); System.exit (0);}} public void Swapvalue () {i = i + 1;} public static void Main (string[] args) {final Test volobj = new test (); Thread mainthread = new Thread () {public void run () {System.out.println ("mainthread start"), while (true) {Volobj.tryexit ( );}}}; Mainthread.start (); Thread swapthread = new Thread () {public void run () {System.out.println ("swapthread start"), while (true) {Volobj.swapvalu E ();}}; Swapthread.start (); try {thread.sleep (10000);} catch (Interruptedexception e) {e.printstacktrace ();}}}
When you use the volatile modifier variable i, when a thread changes the value of I, it is written back to the main memory area, so that each thread is used with the most recent value. But not to replace synchronized,because in the a thread, the I variable in the b thread is 1 o'clock, a time AB thread executes i++ simultaneously. The value of the final I will be 2. Because there is no lock. This needs to be noted.
How volatile modification works in Java multithreading concurrency variable control method