Java uses volatile to implement thread data sharing
Directly on the code to see the effect:
Public classVolatiletestextendsThread {Private volatile BooleanIsRunning =true; Private voidSetrunning (Booleans) {isrunning=s; } @Override Public voidrun () {System.out.println (isrunning); while(isrunning) {//System.out.println ("isrunning true");} System.out.println ("Stop Command"); } Public Static voidMain (string[] args)throwsinterruptedexception {volatiletest T=Newvolatiletest (); T.start (); Thread.Sleep (3000); T.setrunning (false); Thread.Sleep (2000); }}
The effect is as follows:
If the non-volatile while loop does not stop, the isrunning is still true even if setrunning (false) is in a child thread in the main thread.
In Java, when a child thread executes, it makes an area in memory, deliberately copying the variables from the thread to the memory area of the child thread, reducing the interaction of the child thread and the main thread to improve efficiency.
This causes the child thread to be inconsistent with the isrunning value of the main thread.
Adding volatile then forces the child thread to go to the main thread to take the value of the variable.
Java uses volatile to implement thread data sharing