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

CodePudding user response:

reference 1st floor also night reply:
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 in the main function also need to open another thread to invoke the surveillance function B


Thread in the main function of B I opened, I write method is running in a thread, forgot to write the main,

Mainly want to use the variable to change B, then B is A running thread to obtain the latest values to the flag, I checked the Internet A lot of methods, it is changing variable after restarting threads, don't know how to timely access to the thread running the new value,

CodePudding user response:

Your thread calls the code also posted, light your list the code to see no problem

CodePudding user response:

I mean you should be alone in the function call open another thread B listen thread, said first call monitoring function, to change the thread in A listening state, then calls A method to modify the variable after because visibility, so at the moment is to be able to get to the B send_flag latest values
  • Related