I have a runnable gui swing class that sets my variables when the constructor is initialized. When the gui runs, it runs as its own seperate thread. The problem however is when an action-event is triggered on my gui, when I try to access my initialized variables they are reset to their default. After some debugging, it seems that the action-event triggered begins as a thread of its own. How can I access the correct variables in the right thread when processing my action events?
Example code:
public class myGui implements Runnable{
private flag = false;
public myGui(){
flag = true;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("The value of flag is: " + flag); // prints flag is false
}
public void run(){
// Do stuff
}
// More code ...
}
In my example, when initializing the constructor in the thread, flag is set to true. However when the action-event is triggered it will see flag as set to false ignoring my threads variables. How do i fix this?
Thanks
The crucial part here is visibility of your variables across different threads. In the absence of synchronization, the compiler, processor, and runtime can do some downright weird things to the order in which operations appear to execute.
Hence, use the
volatilemodifier on yourflagvariable to ensure that updates to a variable are propagated predictably to other threads.Take a look at the Initial Threads section of Concurrency in Swing. Make sure that UI updates are run in the Event Dispatcher Thread for instance with invokeLater or invokeAndWait. This should give you are clearer understanding of the different threads involved in Swing.