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 wit
I believe a CountDownLatch will do what you want.
final CountDownLatch latch = new CountDownLatch(10);
int delay = 1000;
int period = 1000;
timerPanel.setText(Long.toString(latch.getCount()));
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
latch.countDown();
timerPanel.setText(Long.toString(latch.getCount()));
}
}, delay, period);
try {
latch.await();
}
catch (InterruptedException e) {
e.printStackTrace();
}
timer.cancel();
You should use Thread.sleep
function instead of TimeTask
to halt execution.
TimerTask
is not meant to halt execution, its like a clock running in background. So for your requirement you should go for Thread.sleep
.
Use a Semaphore. Initialize it before declaring the timer task, with 0 permits. In the timer task, use a try/finally block to release the semaphore. In the main thread, acquire the permit from the semaphore.
In your code, join works as specified since it waits for the thread to finish. And no, using a thread for this is not necessary. If you really want to block until a certain time, you don't need a Timer. Get the current time, compute the millis until the future time, and sleep().