且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-01-12 00:02:23

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