LearnFrenzy
Sign in Take a free test

Multithreading · Multithreading Programs · Question 10

Background worker with a progress monitor in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

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);
    }
}

Output Verified by compiling and running

saw halfway: true, processed 100/100
milestones [25%, 50%, 75%, 100%]

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.

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