Java:在继续执行之前等待TimerTask完成

时间:2013-07-01 13:41:50

标签: java multithreading concurrency timer timertask

我有点烦人的问题。现在,我有一段代码片段启动一个线程,在该线程中设置一个计时器,然后退出该线程并继续其生命。我的目的是让程序在继续代码流之前等待TimerTask完成。但是,显然,设置新的TimerTask不会暂停执行以等待定时器运行。

如何设置它以便我的代码到达TimerTask,等待TimerTask过期,然后继续?我甚至应该使用计时器吗?我到处寻找解决方案,但我似乎找不到一个。

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

提前致谢。

编辑:对于重复任务的混乱感到抱歉。我需要重复该任务,因为它是一个倒数计时器,每秒从10脉冲到0脉冲。函数setInterval()最终取消计时器。这是相关的代码:

private final Integer setInterval() {
    if (interval == 1)
        timer.cancel();
    return --interval;
}

3 个答案:

答案 0 :(得分:5)

我相信CountDownLatch会做你想做的事。

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

答案 1 :(得分:0)

您应该使用Thread.sleep函数而不是TimeTask来暂停执行。

TimerTask并不意味着停止执行,它就像一个在后台运行的时钟。因此,根据您的要求,您应该选择Thread.sleep

答案 2 :(得分:0)

使用信号量。在声明计时器任务之前初始化它,允许0。在计时器任务中,使用try / finally块释放信号量。在主线程中,从信号量获取许可证。

在您的代码中,join因为等待线程完成而按指定的方式工作。不,没有必要使用线程。如果你真的想要阻止一段时间,你不需要一个Timer。获取当前时间,计算毫秒直到未来时间,然后睡眠()。

相关问题