繁体   English   中英

Java:等待TimerTask完成后再继续执行

[英]Java: Wait for TimerTask to complete before continuing execution

我有一个烦人的问题。 现在,我有一段代码来启动一个线程,在该线程中设置一个计时器,然后退出该线程并继续其生命。 我的目的是让程序在继续执行代码流之前先等待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;
}

我相信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();

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

TimerTask并非要暂停执行,就像在后台运行的时钟一样。 因此,根据您的要求,您应该选择Thread.sleep

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

在您的代码中,join按照指定的方式工作,因为它等待线程完成。 不,不需要使用线程。 如果您确实要在特定时间之前进行阻止,则不需要计时器。 获取当前时间,计算直到未来时间的毫秒数,然后sleep()。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM