Run a background worker that processes 100 items, updating a volatile progress counter; a monitor in main waits (with join) and then reports. Also record which milestones (25%, 50%, 75%, 100%) the worker reached, in order.
Solution
Main.java
import java.util.ArrayList;
import java.util.List;
public class Main {
static volatile int processed = 0;
public static void main(String[] args) throws InterruptedException {
int total = 100;
List<String> milestones = new ArrayList<>(); // written only by the worker
Thread worker = new Thread(() -> {
for (int i = 1; i <= total; i++) {
processed = i; // single writer: volatile is enough here
int pct = i * 100 / total;
if (pct % 25 == 0 && i * 100 % total == 0) milestones.add(pct + "%");
}
}, "worker");
worker.start();
while (processed < total / 2) Thread.onSpinWait(); // watch progress from main
boolean sawHalfway = processed >= 50;
worker.join();
System.out.println("saw halfway: " + sawHalfway + ", processed " + processed + "/" + total);
System.out.println("milestones " + milestones);
}
}
With one writing thread, a volatile counter is a safe way for others to read progress. The milestone list is read only after join, so it needs no lock.
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!