Java: Wait for TimerTask to complete before continuing execution

后端 未结 3 1232
暖寄归人
暖寄归人 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: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().

提交回复
热议问题