Each time a member variable modified by volatile is accessed by a thread, the value of the member variable is forcibly re-read from the shared memory. In addition, when the member variables change, the thread is forced to write the change value back to the shared memory. In this way, two different threads always see the same value of a member variable at any time. In the Java language specification, it is pointed out that in order to get the best speed, the thread is allowed to save the private copy of shared member variables, and the original value of shared member variables is compared only when the thread enters or leaves the synchronized code block. In this way, when multiple threads interact with an object at the same time, you must notice that the thread needs to get the shared member variable changes in a timely manner. The volatile keyword prompts VM: For this member variable, it cannot store its private copy, but should directly interact with the shared member variable. Suggestion: use volatile on the member variables accessed by two or more threads. You do not need to use this variable when it is already in the synchronized code block or a constant. Because volatile is used to block the necessary code optimization in the VM, the efficiency is relatively low. Therefore, this keyword must be used when necessary.
Generally, if multiple threads collaboratively store and fetch a variable, you generally need to use the synchronized keyword for synchronization, such: public class mytestthread extends mytest implements runnable {private Boolean _ DONE = false; Public synchronized Boolean getdone () {return _ done;} public synchronized void setdone (Boolean B) {_ DONE = B;} public void run () {Boolean done; done = getdone (); While (! Done) {repaint (); try {thread. sleep (100);} catch (interruptedexception IE) {return ;}}} or: public class mytestthread extends mytest implements runnable {private Boolean _ DONE = false; public void setdone (Boolean B) {synchronized (this) {_ DONE = B ;}} public void run () {Boolean done; synchronized (this) {done = _ done ;} while (! Done) {repaint (); try {thread. sleep (100) ;}catch (interruptedexception IE) {return ;}}} however, by using the volatile keyword, We can greatly simplify: public class mytestthread extends mytest implements runnable {private volatile Boolean done = false; Public void run () {While (! Done) {repaint (); try {thread. sleep (100);} catch (interruptedexception IE) {return ;}} public void setdone (Boolean B) {done = B ;}}