java timer线程结束,Java:在继续执行之前等待TimerTask完成

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;

}

解决方案

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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值