Home > Back-end > Ask a questions about thread access to a Shared variable
Ask a questions about thread access to a Shared variable
Time:11-23
Now I have two classes, class A is true for sending the logo position, class B in has been running state (because to receive some information), and then when the send_flag is true class B to send A message (here I use print statements), below is I give simplified logic relationship, Class A { Public static volatile Boolean send_flag=false; Public void change () { Send_flag=true; } }
Class B { Public void listen () { While (true) { If (A.s end_flag) { System. The out. Println (" Hello "); } } } }
And then I run B first, and then in A changing send_flag value, why send_flag in B value has always been false, have been printed out, volatile allows variables have visibility, isn't it? I learn Java didn't take long, also please supervise your older sisters to give directions, thank you
CodePudding user response:
Did you open a thread? You should be in the main function calls, thread visibility refers to, you changed the value, in the thread to another thread is visible Even if you don't open the two threads, you also need to open in the main function another thread to invoke the monitoring function B