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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!