user1031431 user1031431 -4 years ago 75
Java Question

Sharing a variable between multiple different threads

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!

Answer Source

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 immeditately 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download