Tag: string new appears sys CEP ext phenomenon while variable
Volatile-modified variables ensure that each thread can get the latest value of the variable, thus avoiding the appearance of dirty reading of the data.
According to the following example:
Package Sync;public class Volatiletest extends thread{//global variable isrunning add non-volatile effect private/*volatile*/Boolean isrunning = True;private void Setrunning (Boolean isrunning) {this.isrunning = isrunning;} @Overridepublic void Run () {System.out.println ("Enter the Run Method:"); /Loop until isrunning becomes Falsewhile (isrunning) {//...} SYSTEM.OUT.PRINTLN ("Thread Stop");} public static void Main (string[] args) throws Interruptedexception {//new instance object Volatiletest RT = new Volatiletest ();//Call RU N Method Rt.start (); Thread.Sleep (3000);//Set isrunning variable to falsert.setrunning (false); System.out.println ("The value of isrunning has become false"); Thread.Sleep (3000); System.out.println (rt.isrunning);}}
No volatile output results:
As you can see, the thread is not stopped and is still circulating in the run () method,
We set the global variable isrunning to False in the main method, and the thread does not take effect when executing the Run method
Add volatile output results:
You can see that the thread received the IsRunning value changed in time.
Conclusion:
(1) Do not use volatile:
When a thread executes a run method that uses a global variable, the value of the global variable is loaded at the beginning of the first time, and is no longer loaded
(2) Use volatile:
When a thread executes a run method that uses a global variable, the value of the global variable is initially loaded, and whenever a volatile-modified variable is changed, the Run method is notified to reload the new value
The value of the global variable isrunning is placed in main memory 1
When the thread executes the Run method, the value inside it is in another independent memory area 2
Each time the Run method executes, it reads the value of the isrunning of main memory 1 at the first execution and copies the independent memory to the Run Method 2
Java concurrency Programming _volatile keyword Usage (ii)