I want to share a variable between multiple threads like this:
boolean flag = true;
T1 main = new T1();
T2 help = new T2();
main.start();
help.start();
I’d like to share flag between main and help thread where these are two different Java classes I’ve created. Is any way to do this? Thanks!
Both
T1andT2can refer to a class containing this variable.You can then make this variable volatile, and this means that
Changes to that variable are immediately visible in both threads.
See this article for more info.
And note the pros/cons of using
volatilevs more complex means of sharing state.