LearnFrenzy
Sign in Take a free test

Multithreading · Multithreading Programs · Question 5

Cancellable countdown timer thread in Java Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

Run a countdown from 5 in a separate thread (ticking every 20 ms, recording each tick), and in a second run interrupt it after the 2nd tick; print the ticks recorded in each run.

Solution
Main.java
import java.util.ArrayList;
import java.util.List;

public class Main {
    static List<Integer> countdown(int from, int interruptAfterTicks) throws InterruptedException {
        List<Integer> ticks = new ArrayList<>();
        Object lock = new Object();
        Thread timer = new Thread(() -> {
            try {
                for (int i = from; i >= 1; i--) {
                    synchronized (lock) { ticks.add(i); lock.notifyAll(); }
                    Thread.sleep(20);
                }
            } catch (InterruptedException e) {
                synchronized (lock) { ticks.add(-1); }          // -1 marks "cancelled"
            }
        });
        timer.start();
        if (interruptAfterTicks > 0) {
            synchronized (lock) { while (ticks.size() < interruptAfterTicks) lock.wait(); }
            timer.interrupt();
        }
        timer.join();
        synchronized (lock) { return new ArrayList<>(ticks); }
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println("full run:  " + countdown(5, 0));
        System.out.println("cancelled: " + countdown(5, 2));
    }
}

Output Verified by compiling and running

full run:  [5, 4, 3, 2, 1]
cancelled: [5, 4, -1]

main waits (with wait/notify) until two ticks are recorded, then interrupts; the timer is sleeping, receives InterruptedException and stops cleanly.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links