I'm having a bit of an annoying problem. Right now, I have a snippet of code that starts a thread, sets a timer within that thread, and then exits that thread and continues with its life. My intent here was for the program to wait for the TimerTask to complete before continuing with code flow. However, obviously, setting up a new TimerTask doesn't pause execution to wait for the timer to run down.
How do I set this up so that my code reaches the TimerTask, waits for the TimerTask to expire, and then continues? Should I even be using a Timer at all? I've looked everywhere for a solution, but I Can't seem to find one.
timer = new Timer();
Thread t = new Thread(new Runnable(){
boolean isRunning = true;
public void run() {
int delay = 1000;
int period = 1000;
interval = 10;
timerPanel.setText(interval.toString());
//Scheduling the below TimerTask doesn't wait
//for the TimerTask to finish before continuing
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
timerPanel.setText(setInterval().toString());
}
}, delay, period);
System.out.println("Thread done.");
}
});
t.start();
try {
t.join(); //doesn't work as I wanted
} catch (InterruptedException e) {
e.printStackTrace();
}
endTask();
Thanks in advance.
EDIT: Sorry for the confusion about the repeated task. I need the task to repeat because it's a countdown timer that pulses every second from 10 to 0. The function setInterval() eventually cancels the timer. Here's the relevant code:
private final Integer setInterval() {
if (interval == 1)
timer.cancel();
return --interval;
}