Java: Wait for TimerTask to complete before continuing execution

后端 未结 3 1227
暖寄归人
暖寄归人 2021-01-23 13:08

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

相关标签:
3条回答
  • 2021-01-23 13:36

    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();
    
    0 讨论(0)
  • 2021-01-23 13:54

    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.

    0 讨论(0)
  • 2021-01-23 13:56

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

    0 讨论(0)
提交回复
热议问题