This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
How do I pass a update a variable to all running Threads?
I know I can pass variables to a Thread by making a class implement Runnable, making a constructor for the class, create an instance of the class to pass in the variables then start the Thread.
But how do I update a variable into a Thread that is already running and this updated variable must be visible to all the Threads that are running at that time?
I am thinking...
Yeah yeah, I know, I need to put in a Timer for the Thread to run for sometime too.
But, this way if I change the value of value in vTU during runtime, like maybe take in an input from the user at runtime and store it in vTU, will the the value in the vTU objects in both Threads change? Thus, changing the output?
Anayonkar Shivalkar wrote:if two threads are dealing with same reference, and some change is made to that in one thread, is it reflected in other thread?
If you want the other threads to see it, then you need to declare the variable volatile, or synchronize all access to it, or use an appropriate java.util.concurrent.atomic.AtomicXxx object. If you don't do this, there's no guarantee of when or even if the other threads will see the new value.