Java: Wait for TimerTask to complete before continuing execution

后端 未结 3 1271
暖寄归人
暖寄归人 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();
    

提交回复
热议问题