Interruptible Countdown

I am trying to implement an interruptible countdown, but somehow can't figure it out.

I want a countdown to be started by an event and when the countdown reaches 0 stuff is done, unless a new event occured at which point I want the countdown to stop or restart (depending on the specific event).

It can't be that hard, but so far I am not sure how to even start.

1 answer

  • answered 2018-07-11 05:52 Ben Barkay

    What you are looking for sounds similar to "debouncing" (which has an answer: implementing debounce in Java), which is time based.

    Perhaps a CountDownLatch could also be of use:

    int count = 4; // the countdown amount
    CountDownLatch latch = new CountDownLatch(count);
    // You could wait until the countdown reaches 0. This is blocking though,
    // so you likely want either this or the counting down to happen on a separate thread.
    latch.await(); // will wait until latch reached 0
    // To count down, call countDown like so:
    // To check the count you can call getCount