Sharing a variable between multiple different threads

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.

Leave a Comment