Java:在继续执行之前等待TimerTask完成 [英] Java: Wait for TimerTask to complete before continuing execution

查看:1286
本文介绍了Java:在继续执行之前等待TimerTask完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点烦人的问题。现在,我有一段代码片段启动一个线程,在该线程中设置一个计时器,然后退出该线程并继续其生命。我的目的是让程序在继续代码流之前等待TimerTask完成。但是,显然,设置一个新的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.

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

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

提前致谢。

编辑:对不起有关重复任务的困惑。我需要重复该任务,因为它是一个倒数计时器,每秒从10到0脉冲。函数setInterval()最终取消计时器。以下是相关代码:

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;
}


推荐答案

我相信 CountDownLatch 将执行您想要的操作。

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

这篇关于Java:在继续执行之前等待TimerTask完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆