š§© Jigsaw Puzzle Builder (Parallel Parts) Concurrency Problem
š§© The Problem
Weāre building a digital jigsaw puzzle game (or simulation) where:
The puzzle has many pieces (hundreds or thousands).
Each piece can be placed independently unless it connects to another.
We want to speed up building the puzzle by letting multiple workers (threads) place pieces at the same time.
Solution Approaches
1ļøā£ Step 1 ā The Naive Single-Threaded Approach
Imagine we have a jigsaw puzzle with 1,000 pieces.
We write a simple loop:
public class PuzzleBuilder {
public static void main(String[] args) {
for (int piece = 1; piece <= 1000; piece++) {
placePiece(piece);
}
}
static void placePiece(int id) {
System.out.println("Placed piece " + id);
try { Thread.sleep(10); } catch (InterruptedException e) {}
}
}
š Idea: One person places all pieces in order.
ā
Works fine for small puzzles.
ā But slow for large puzzles ā only one worker is active.
The Real-World Problem
In real life:
Multiple people can work on different parts of the puzzle at the same time.
We donāt need to place pieces in strict numeric order ā only in correct locations.
Our single-thread version wastes potential parallelism.
