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 T1
and T2
can 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.
Volatile variables share the visibility features of synchronized but none of the atomicity features. This means that threads will automatically see the most up-to-date value for volatile variables. They can be used to provide thread safety, but only in a very restricted set of cases: those that do not impose constraints between multiple variables or between a variable's current value and its future values.
And note the pros/cons of using volatile
vs more complex means of sharing state.