I have a thread z
that is created when a certain JButton begin
is clicked. Inside the run method of that thread, I need to include a dynamic variable val
which changes its value periodically. Val
has been declared globally.
This change is modeled correctly by the stateChanged
function of a JSlider, which continues to print out the correct value for val
in the console. However, in my run
method, the variable val
does not change as needed. It stays constant as the initial value when the Thread was created.
Here are my functions below:
int val;
Thread z;
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(step)) {
simulation();
}
else if (e.getSource().equals(begin)) {
if (running==false) {
running = true;
z = new Thread(this);
z.start();
}
}
else if (e.getSource().equals(end)) {
running = false;
}
}
@Override
public void stateChanged(ChangeEvent e) {
val = slider.getValue();
System.out.println(val);
}
@Override
public void run() {
while (running==true) {
simulation();
try {
Thread.sleep(val+200); //SHOULD BE DYNAMIC
} catch (Exception e) {
e.printStackTrace();
}
}
}
Any thoughts on how I can change the variable val
to be dynamic would be greatly appreciated.
Thank you!
The problem is your val
is NOT volatile
so whenever the main
Thread
updates the variable the runnable()
Thread
is NOT able to view it.
Similarly ensure that you are marking running
variable (used inside while
loop) as volatile
, otherwise the runnable()
thread will run forever (without receiving the update from the other thread).
What is volatile? What does it mean?
In simple words, marking a variable as volatile
makes the writes of one thread visible to the other threads. This is required because when a thread is writing to a variable, the variable data is cached (local to the thread) and it might NOT be visible to the other threads, until the writing thread flushes the data. So volatile
ensures that the data is not cached rather it is always written/fetched from main memory.
I suggest yo to understand the basics of thread communication by referring here.