I'm working on an application in Java that is required to update its results every second until it is stopped. For 30 seconds it will call a certain set of methods each second, then another set for the next 30 seconds, then the first set again and so on. Since I want to be able to stop and restart the calculations that are performed in the background whenever I want, I've made a GUI and a couple of buttons to start and stop the new thread, as well as a means to display the results every second.
The problem I've run into is that once the new thread is started I can't switch back to the GUI until it is completed, and since the thread will keep going until I tell it to stop, I end up not being able to exit an infinite loop. Could I fix this by placing the GUI in a thread of its own so that both threads are run at the same time? And if so, how would I go about doing that from inside the GUI?
I'm working with more than one class so I don't want to post irrelevant stuff.
public class GUI extends javax.swing.JFrame implements Runnable{
Graphics g;
Threads thread = new Threads();
private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {
thread.run()
}
[..]
private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {
thread.stop()
}
}
public class Threads implements Runnable{
boolean opened=false;
road first = new road();
public void run() {
opened=true;
first.standardInitialization();
while(opened){
for(int i=0; i<30 && opened; i++){
try {
first.redLightAction();
System.out.println("cars: " + first.firstLight.cars);
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Threads.class.getName()).log(Level.SEVERE, null, ex);
}
}
for(int i=0; i<30 && opened; i++){
try {
first.greenLightAction();
second.greenLightAction();
System.out.println("cars: " + first.firstLight.cars);
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Threads.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public void stop(){
opened=false;
}
}