This is a very conceptual question.
Let’s say I have 2 separate threads. Thread A continually gets the time and stores it as a variable, and thread B continually gets the time from thread B’s variable and does something with it.
The moment thread B accesses the variable in thread A, does thread A stop running until the operation is finished?
To expand, what if you had 3 threads, Thread A to get the current time and set it as a variable in Thread B, And then thread C to read the variable.
If Thread A is in the middle of assigning the variable the moment thread C comes to read it, does thread stop running until A is finished?
Thanks for the great answers, but now I have 1 more question. If they would interfere, what is the preferred solution to make the multiple threads not compete when communicating. (Conceptually) what would you do to make it so these threads could share the value of the variable while remaining as fast as possible individually?
Memory and thrads are two entirely different things. Even a variable that is part of a class which represents a thread is just memory like any other that any thread can access.
However, what complicates this and does in fact cause a slowdown is processor caches: in order for two threads running on different CPUs to access the same piece of memory and “see” each other’s changes, the CPU caches have to be synchronized, which can completely negate the (massive) speed advantages of these caches if it happens a lot.
Note that because of caches, thread B may actually see an outdated value of the variable for an arbitrarily long time unless both access the variable within a synchronized block, or the variable is declared with the keyword
volatile.