Eragon20 Eragon20 - 1 year ago 76
Java Question

Using a dynamic variable with threads in Java

I have a thread

that is created when a certain JButton
is clicked. Inside the run method of that thread, I need to include a dynamic variable
which changes its value periodically.
has been declared globally.
This change is modeled correctly by the
function of a JSlider, which continues to print out the correct value for
in the console. However, in my
method, the variable
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)) {

else if (e.getSource().equals(begin)) {
if (running==false) {
running = true;
z = new Thread(this);

else if (e.getSource().equals(end)) {
running = false;

public void stateChanged(ChangeEvent e) {
val = slider.getValue();

public void run() {
while (running==true) {
try {
Thread.sleep(val+200); //SHOULD BE DYNAMIC
} catch (Exception e) {


Any thoughts on how I can change the variable
to be dynamic would be greatly appreciated.

Thank you!

Answer Source

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.

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