Home > Back-end >  Java Shared variable visibility problem
Java Shared variable visibility problem

Time:09-18

Package volatilex;

Public class VolatileMain {

Private static Boolean flag=false;

Public static void main (String [] args) {
New Thread (() - & gt; {
System. The out. Println (" start ");
while (! Flag) {
}
System. The out. Println (" run end ");
}). The start ();
New Thread (() - & gt; {
System. The out. Println (" init begin ");
init();
System. The out. Println (" init end ");
}). The start ();
}

Private static void init () {
flag=true;
}

}

Print the results below

Start
Init begin
Init end
The run end

CodePudding user response:

Why not add a volatile can also visible?

CodePudding user response:

This is a thread of the atomicity of randomness and code
Thread 1 print after the start, can guarantee that it will continue to perform while (! Flag)? Maybe just print out the start, switch to the thread 2 performed, thread 2 changed flag, then switch to the thread 1 continue, that while (! Flag) is not set up, of course,

CodePudding user response:

You changed to the following try again

 private static Boolean flag=false; 
Public static void main (String [] args) {
New Thread (() - & gt; {
System. The out. Println (" start ");
while (! Flag) {
}
System. The out. Println (" run end ");
}). The start ();
New Thread (() - & gt; {
System. The out. Println (" init begin ");
Try {thread.sleep (10); } the catch (Exception e) {}//sleep here, guarantee thread 1 enters the while (! Flag) cycle
init();
System. The out. Println (" init end ");
}). The start ();
}

Private static void init () {
flag=true;
}
  • Related