LOW LEVEL DESIGN · MACHINE CODING · EASY · 28 OF 42

Design a Traffic Signal System: LLD with Java Code

A traffic signal controller designed and coded: an intersection with two crossing roads, phases as States (green, yellow, all red, walk, emergency green, flashing red), timing in one record, a simulated clock instead of sleeps, walk buttons, emergency vehicle override, a conflict monitor that makes two crossing greens impossible, signals as observers, and the follow-ups, with a full Java 17 solution.

Patterns usedStateObserver

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
1 / 21

Press play to hear the narration, or step through at your own pace. The full Java code is below.

Full Java solution

One file, Java 17, 327 lines, with a small main() demo. Save it as TrafficSignal.java, then run javac TrafficSignal.java && java TrafficSignal.

import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;

/** A four-way junction controller: phases as States, a simulated clock, walk buttons, emergency override. */
public class TrafficSignal {

    // ---------- the model ----------
    enum Axis {
        NORTH_SOUTH, EAST_WEST;

        Axis other() { return this == NORTH_SOUTH ? EAST_WEST : NORTH_SOUTH; }
    }

    enum Light { RED, YELLOW, GREEN }

    enum Direction {
        NORTH(Axis.NORTH_SOUTH), SOUTH(Axis.NORTH_SOUTH), EAST(Axis.EAST_WEST), WEST(Axis.EAST_WEST);

        final Axis axis;

        Direction(Axis axis) { this.axis = axis; }
    }

    /** All durations in seconds. minGreen protects drivers from a green that flickers off at once. */
    record Timing(int greenNorthSouth, int greenEastWest, int yellow, int allRed, int walk, int minGreen) {
        int green(Axis a) { return a == Axis.NORTH_SOUTH ? greenNorthSouth : greenEastWest; }
    }

    /** Simulated clock: the demo moves time forward, nothing sleeps. */
    static final class SimClock {
        private long now;

        long now() { return now; }

        void advance(long seconds) { now += seconds; }
    }

    // ---------- phases: the State pattern ----------
    interface Phase {
        String name();

        Light lightFor(Axis a);

        default boolean walk() { return false; }

        /** How long this phase lasts once entered. */
        long duration(Controller c);

        /** Which phase comes next when the time is up. */
        Phase next(Controller c);

        /** How this phase reacts to a walk button press. Default: just wait for the next all-red. */
        default void onWalkRequest(Controller c) {}

        /** How this phase reacts to an emergency vehicle. Default: let the phase finish safely. */
        default void onEmergency(Controller c, Axis from) {}

        default void onEmergencyCleared(Controller c) {}
    }

    record Green(Axis axis) implements Phase {
        public String name() { return axis + " GREEN"; }

        public Light lightFor(Axis a) { return a == axis ? Light.GREEN : Light.RED; }

        public long duration(Controller c) { return c.timing.green(axis); }

        public Phase next(Controller c) { return new Yellow(axis); }

        @Override
        public void onWalkRequest(Controller c) { c.endNoEarlierThan(c.phaseStart + c.timing.minGreen()); }

        @Override
        public void onEmergency(Controller c, Axis from) {
            if (from == axis) c.switchNow(new EmergencyGreen(axis)); // already green: just hold it
            else c.endNoEarlierThan(c.phaseStart + c.timing.minGreen()); // then yellow, never skip it
        }
    }

    record Yellow(Axis axis) implements Phase {
        public String name() { return axis + " YELLOW"; }

        public Light lightFor(Axis a) { return a == axis ? Light.YELLOW : Light.RED; }

        public long duration(Controller c) { return c.timing.yellow(); }

        public Phase next(Controller c) { return new AllRed(axis.other()); }
    }

    /** Every light red for a moment so the junction clears. The decision point for what runs next. */
    record AllRed(Axis upNext) implements Phase {
        public String name() { return "ALL RED"; }

        public Light lightFor(Axis a) { return Light.RED; }

        public long duration(Controller c) { return c.timing.allRed(); }

        public Phase next(Controller c) {
            if (c.emergencyFrom != null) return new EmergencyGreen(c.emergencyFrom);
            if (c.walkWaiting) {
                c.walkWaiting = false;
                return new Walk(upNext);
            }
            return new Green(upNext);
        }
    }

    /** All cars red, pedestrians cross every road. */
    record Walk(Axis upNext) implements Phase {
        public String name() { return "WALK"; }

        public Light lightFor(Axis a) { return Light.RED; }

        @Override
        public boolean walk() { return true; }

        public long duration(Controller c) { return c.timing.walk(); }

        public Phase next(Controller c) { return new AllRed(upNext); }
    }

    /** Green held for the emergency vehicle's road until someone clears it. */
    record EmergencyGreen(Axis axis) implements Phase {
        public String name() { return axis + " EMERGENCY GREEN"; }

        public Light lightFor(Axis a) { return a == axis ? Light.GREEN : Light.RED; }

        public long duration(Controller c) { return Long.MAX_VALUE / 4; }

        public Phase next(Controller c) { return new Yellow(axis); }

        @Override
        public void onEmergencyCleared(Controller c) { c.endNoEarlierThan(c.clock.now()); }
    }

    /** Fail-safe: something broke, so every approach treats the junction as a stop sign. */
    record FlashingRed(String reason) implements Phase {
        public String name() { return "FLASHING RED (" + reason + ")"; }

        public Light lightFor(Axis a) { return Light.RED; }

        public long duration(Controller c) { return Long.MAX_VALUE / 4; }

        public Phase next(Controller c) { return this; }
    }

    // ---------- signals and the safety monitor ----------
    interface PhaseListener { void onPhase(long time, Phase phase); }

    /** One signal head per approach. It only shows what the controller tells it: an observer. */
    static final class Signal implements PhaseListener {
        final Direction direction;
        Light light = Light.RED;
        boolean walk;

        Signal(Direction d) { this.direction = d; }

        @Override
        public void onPhase(long time, Phase p) {
            light = p.lightFor(direction.axis);
            walk = p.walk();
        }
    }

    /** Checks every change before it reaches the lamps, like the conflict monitor in a real cabinet. */
    static final class ConflictMonitor {
        int checks;

        String violation(Phase from, Phase to) {
            checks++;
            if (to.lightFor(Axis.NORTH_SOUTH) != Light.RED && to.lightFor(Axis.EAST_WEST) != Light.RED)
                return "conflicting greens";
            for (Axis a : Axis.values())
                if (from.lightFor(a) == Light.GREEN && to.lightFor(a) == Light.RED)
                    return "green to red, no yellow";
            boolean carsMove = to.lightFor(Axis.NORTH_SOUTH) != Light.RED
                    || to.lightFor(Axis.EAST_WEST) != Light.RED;
            if (to.walk() && carsMove) return "walk with moving cars";
            return null;
        }
    }

    // ---------- the controller ----------
    static final class Controller {
        final SimClock clock;
        final Timing timing;
        private final ConflictMonitor monitor = new ConflictMonitor();
        private final List<PhaseListener> listeners = new ArrayList<>();
        Phase phase = new AllRed(Axis.NORTH_SOUTH); // power on: everything red first
        long phaseStart, phaseEnd;
        boolean walkWaiting;
        Axis emergencyFrom;

        Controller(SimClock clock, Timing timing) {
            this.clock = clock;
            this.timing = timing;
            this.phaseEnd = timing.allRed();
        }

        void subscribe(PhaseListener l) {
            listeners.add(l);
            l.onPhase(clock.now(), phase);
        }

        /** Called on every clock tick: move through as many phases as the elapsed time allows. */
        synchronized void tick() {
            while (clock.now() >= phaseEnd) enter(phase.next(this), phaseEnd);
        }

        synchronized void pressWalk() {
            if (walkWaiting) return; // pressing again does nothing
            walkWaiting = true;
            phase.onWalkRequest(this);
            tick();
        }

        synchronized void emergency(Axis from) {
            if (emergencyFrom != null) return; // first come, first served
            emergencyFrom = from;
            phase.onEmergency(this, from);
            tick();
        }

        synchronized void emergencyCleared() {
            emergencyFrom = null;
            phase.onEmergencyCleared(this);
            tick();
        }

        // Helpers the phases call. They can only end a phase sooner, never break the order.
        void endNoEarlierThan(long t) { phaseEnd = Math.min(phaseEnd, Math.max(t, clock.now())); }

        void switchNow(Phase p) { enter(p, clock.now()); }

        private void enter(Phase next, long at) {
            String bad = monitor.violation(phase, next);
            if (bad != null) next = new FlashingRed(bad);
            phase = next;
            phaseStart = at;
            phaseEnd = at + next.duration(this);
            for (PhaseListener l : listeners) l.onPhase(at, next);
        }
    }

    // ---------- the intersection ----------
    final Controller controller;
    final Map<Direction, Signal> signals = new EnumMap<>(Direction.class);

    TrafficSignal(SimClock clock, Timing timing) {
        controller = new Controller(clock, timing);
        for (Direction d : Direction.values()) {
            Signal s = new Signal(d);
            signals.put(d, s);
            controller.subscribe(s);
        }
    }

    /** The safety rule, checked from the lamps themselves: two crossing roads never both move. */
    boolean safe() {
        boolean ns = signals.get(Direction.NORTH).light != Light.RED;
        boolean ew = signals.get(Direction.EAST).light != Light.RED;
        boolean walking = signals.get(Direction.NORTH).walk;
        return !(ns && ew) && !(walking && (ns || ew));
    }

    // ---------- demo ----------
    static void check(boolean ok, String what) {
        if (!ok) throw new AssertionError(what);
    }

    public static void main(String[] args) {
        SimClock clock = new SimClock();
        TrafficSignal junction = new TrafficSignal(clock, new Timing(30, 20, 4, 2, 12, 8));
        Controller c = junction.controller;
        c.subscribe((t, p) -> System.out.printf("t=%3ds  %s%n", t, p.name()));

        long walkPressed = -1, walkStarted = -1;
        List<Long> sirens = new ArrayList<>(), emergencyGreens = new ArrayList<>();
        for (int t = 1; t <= 200; t++) {
            clock.advance(1);
            if (t == 10) {
                System.out.println("t= 10s  walk button pressed");
                walkPressed = t;
                c.pressWalk();
            }
            if (t == 70 || t == 150) { // first while its road is red, then while it is green
                System.out.printf("t=%3ds  ambulance approaching on EAST_WEST%n", t);
                sirens.add((long) t);
                c.emergency(Axis.EAST_WEST);
            }
            if (t == 100 || t == 170) {
                System.out.printf("t=%3ds  ambulance has passed%n", t);
                c.emergencyCleared();
            }
            c.tick();
            if (walkStarted < 0 && c.phase.walk()) walkStarted = t;
            if (c.phase instanceof EmergencyGreen && emergencyGreens.size() < sirens.size())
                emergencyGreens.add((long) t);
            check(junction.safe(), "unsafe lights at t=" + t);
            check(!(c.phase instanceof FlashingRed), "monitor tripped at t=" + t);
        }
        long wait1 = emergencyGreens.get(0) - sirens.get(0), wait2 = emergencyGreens.get(1) - sirens.get(1);
        System.out.println("Walk waited " + (walkStarted - walkPressed) + "s, ambulance waited " + wait1
                + "s then " + wait2 + "s, " + c.monitor.checks + " changes checked, 0 conflicts");
        check(walkStarted - walkPressed <= 6, "walk should be served after yellow and all red");
        check(wait1 <= 6 && wait2 == 0, "ambulance waits at most yellow plus all red");

        // A broken phase is caught before it reaches the lamps.
        SimClock clock2 = new SimClock();
        TrafficSignal broken = new TrafficSignal(clock2, new Timing(30, 20, 4, 2, 12, 8));
        Phase bug = new Phase() {
            public String name() { return "BUGGY BOTH GREEN"; }

            public Light lightFor(Axis a) { return Light.GREEN; }

            public long duration(Controller x) { return 10; }

            public Phase next(Controller x) { return this; }
        };
        broken.controller.switchNow(bug);
        Phase now = broken.controller.phase;
        System.out.println("Fault test: " + now.name() + ", lamps safe: " + broken.safe());
        check(now instanceof FlashingRed && broken.safe(), "monitor must block the fault");
    }
}

Notes

Requirements

Fix the scope. One crossroads with a north-south road and an east-west road. Each approach has a red, yellow and green light. The two roads take turns, and each road can have its own green time. A walk button stops all cars so people can cross. An emergency vehicle gets green on its road as soon as it is safe. Above everything: two crossing roads never show green together. Turn arrows and cameras are out of scope.

Ask for the numbers and the failure rules. Green is thirty seconds for north-south and twenty for east-west. Yellow is four seconds and an all-red gap is two. The walk phase is twelve seconds. A green must last at least eight seconds, so drivers are not surprised. Two ambulances at once? The first one wins. And if the logic ever fails, every light flashes red, which drivers treat as a four-way stop.

Requirements
  • one crossroads: north-south and
  • east-west roads
  • lights: red, yellow, green
  • roads take turns, timed per road
  • walk button: all cars stop,
  • people cross
  • emergency vehicle: its road
  • gets green as soon as safe
  • never two crossing greens
  • out of scope: turn arrows, cameras
Clarify first
  • green times?
  • north-south 30s, east-west 20s
  • yellow? 4s, all red? 2s
  • walk phase? 12s, all roads
  • shortest green? 8s minimum
  • two ambulances at once?
  • first one wins, then the next
  • what if the logic fails?
  • flash red: a four-way stop

Entities

Underline the nouns: intersection, road, signal, light, phase, timer, button. The intersection has four signals, one per approach. The controller is the brain: it holds the current phase, when that phase ends, and any waiting requests. A phase is one step of the cycle, like north-south green. Timing is a small record of durations, and the clock is injected so tests control time.

Class diagram

In code: an axis is either north-south or east-west, and knows the other one. A light is red, yellow or green. Each of the four directions belongs to an axis, because north and south always show the same colour. Timing is one immutable record with the green time per road, yellow, all red, walk and minimum green, so a new timing plan for rush hour is just a different record.

Value types
enum Axis { NORTH_SOUTH, EAST_WEST;
  Axis other() }
enum Light { RED, YELLOW, GREEN }
enum Direction { NORTH, SOUTH,
  EAST, WEST; final Axis axis; }
record Timing(int greenNorthSouth,
  int greenEastWest, int yellow,
  int allRed, int walk, int minGreen)

The naive way

The first version people write is one loop with a colour variable, a chain of if statements, and sleep calls. Every new rule, a walk button, an ambulance, a night mode, adds a check inside every branch, and they slowly disagree with each other. Worse, testing a thirty second green means waiting thirty real seconds. We fix both problems: the State pattern for the rules, and a simulated clock for time.

Naive controller
while (true) {
  if (color == GREEN) {
    if (walkPressed) ...
    if (siren) ...
    sleep(30_000); color = YELLOW;
  } else if (color == YELLOW) {
    if (siren) ...
  } ...
}
every new rule: edit every branch

State pattern

Each phase becomes a small class implementing one interface: the State pattern. A phase answers three questions: what light does each road see, how long do I last, and which phase comes next. It also decides how to react to events, like a walk button or a siren, with safe defaults that do nothing. The controller never asks which phase it is in. It just delegates to the current one.

interface Phase
Light lightFor(Axis a);
long duration(Controller c);
Phase next(Controller c);
default void onWalkRequest(c) {}
default void onEmergency(c, axis) {}
default void onEmergencyCleared(c) {}

Green, Yellow, AllRed, Walk,
  EmergencyGreen, FlashingRed

The normal cycle

Here is the normal cycle. North-south green for thirty seconds, then yellow for four, then all red for two, then east-west green for twenty, yellow, all red, and back to the start: sixty two seconds in total. Notice the shape: green always goes to yellow, yellow always goes to all red, and only the all-red phase decides what runs next. That one decision point is where walk and emergency requests plug in.

One full cycle
  • NS GREEN 30s
  • NS YELLOW 4s
  • ALL RED 2s
  • EW GREEN 20s
  • EW YELLOW 4s
  • ALL RED 2s
  • cycle = 62 seconds
  • Yellow.next() is always AllRed
  • AllRed.next() picks what is next

Safety by design

Safety comes from the structure, not from careful if statements. Every phase lights at most one axis. A green can only be followed by its own yellow, and every change of road passes through all red, so the junction clears before the other road moves. Even the emergency path follows this route. Events can make a phase end sooner, but they can never jump the order.

Why it is safe
  • Green(a): only a is green
  • Yellow(a): only a is yellow
  • AllRed: nobody moves
  • Walk: nobody moves
  • Emergency(a): only a is green
  • Green.next() is Yellow, always
  • any change of road passes
  • through AllRed

Conflict monitor

Real signal cabinets also have an independent conflict monitor, and so does our design. Every phase change passes through it first. It rejects two axes that are not red, a green that jumps straight to red, and a walk signal while cars can move. If any rule is broken, the controller enters flashing red instead. The demo injects a buggy phase that turns both roads green, and the monitor catches it.

ConflictMonitor.violation()
both axes not RED?
  -> "conflicting greens"
GREEN straight to RED?
  -> "green to red, no yellow"
walk while cars can move?
  -> "walk with moving cars"

violation: enter FlashingRed
  instead of the bad phase

Timing without sleep

Now time. The controller does not sleep. It stores when the current phase ends. Each tick compares the clock with that deadline, and while the deadline has passed it enters the next phase, starting it exactly at the old deadline so no time drifts. On a real device a timer calls tick ten times a second. In tests a simulated clock moves forward one second at a time, so two hundred seconds run instantly.

Controller.tick()
while (clock.now() >= phaseEnd)
  enter(phase.next(this), phaseEnd);

enter(next, at):
  phaseStart = at;
  phaseEnd = at + next.duration(this);

real device: tick every 100 ms
test: clock.advance(1) in a loop

Walk button

The walk button shows why states are useful. Pressing it sets a waiting flag and tells the current phase. A green phase reacts by ending early, but never before its minimum green. Yellow and all red do nothing, because they end soon anyway. Then the all-red phase sees the flag, clears it, and returns a walk phase instead of the next green. In the demo, a press at ten seconds gives walk at sixteen seconds.

Walk request
pressWalk(): walkWaiting = true;
  phase.onWalkRequest(this);

Green: end at start + minGreen
Yellow, AllRed: do nothing
AllRed.next(): if walkWaiting
  clear it, return new Walk(..)

press at 10s: yellow 10s,
  all red 14s, walk 16s

Emergency override

Emergency override follows the same idea. If the ambulance's road is already green, the green phase simply swaps itself for an emergency green that is held, so the light never changes in front of it. If the other road is green, that green ends after its minimum time, and the normal yellow and all red follow. All red always gives the emergency road priority. The emergency green lasts until someone clears it.

onEmergency(from)
  • Green on the same road:
  • switch to EmergencyGreen now
  • Green on the other road:
  • end after minimum green,
  • then yellow, then all red
  • Yellow, Walk: finish safely
  • AllRed.next(): emergency first
  • EmergencyGreen: held until
  • emergencyCleared()

Flow: an ambulance

Follow the demo. At seventy seconds north-south has been green for fourteen seconds, more than the minimum, when an ambulance approaches on east-west. North-south goes yellow at once, all red at seventy four, and east-west gets an emergency green at seventy six: six seconds, the fastest safe time. When it passes at one hundred, east-west goes yellow and normal cycling resumes. A second ambulance on an already green road waits zero seconds.

Observer: signals

The lamps themselves are observers. Each signal subscribes to the controller and, on every phase change, asks the new phase which light its axis should show and whether walk is lit. The controller does not know how many signals exist. A countdown display for pedestrians, a log for the traffic department, or a test that records every phase all subscribe the same way.

Concurrency

In a real cabinet, button presses, siren detectors and the timer arrive on different threads. If a walk press and a tick change the phase at the same moment, the order could break. So every public method of the controller is synchronized, and all phase changes go through one private method under that lock. Pressing walk twice is harmless. An alternative is one event-loop thread that reads events from a queue.

Thread safety
  • tick, pressWalk, emergency and
  • emergencyCleared: synchronized
  • phase changes happen in one
  • place, under one lock
  • pressing walk twice: no-op
  • second siren: ignored until clear
  • or: one event-loop thread and
  • a queue of events

Extensibility

Extensions fit the same shape. Left turn arrows are more phases plus more conflict rules in the monitor. Road sensors can extend a green while cars keep arriving. Night mode is a flashing yellow phase. A rush hour plan is just a different timing record. A green wave along a main road offsets the cycle start of neighbouring junctions, and a city-wide coordinator can push new timing plans to each controller.

Extension points
  • turn arrows: more phases
  • and more conflict rules
  • car sensors: extend green
  • while cars keep coming
  • night mode: flashing yellow
  • rush hour: a new Timing record
  • green wave: offset the start
  • of nearby junctions
  • many junctions: a central
  • coordinator sends Timing

Testing

The full code is below the player. A loop advances the simulated clock one second at a time for two hundred seconds, presses the walk button, and sends two ambulances, one on a red road and one on a green road. After every second it checks the lamps directly: never two crossing roads moving, never walk with moving cars. Finally it injects a buggy phase and proves the monitor turns it into flashing red.

Run it
t= 10s  walk button pressed
t= 10s  NORTH_SOUTH YELLOW
t= 16s  WALK
t= 70s  ambulance on EAST_WEST
t= 76s  EAST_WEST EMERGENCY GREEN
t=150s  ambulance on EAST_WEST
t=150s  EAST_WEST EMERGENCY GREEN
Walk waited 6s, ambulance 6s then 0s
22 changes checked, 0 conflicts
Fault test: FLASHING RED

Follow-ups

Expect follow-ups. Why the State pattern instead of a switch? Each phase keeps its own rules, and new phases do not touch old ones. Why an all-red gap? It lets cars that entered on yellow clear the junction. How do you test timing? Inject a clock. Ambulances from both roads? Queue them and serve one after another. And if the controller itself crashes, the hardware falls back to flashing red.

Follow-ups to expect
  • why State, not a switch?
  • why an all-red gap?
  • how do you test timing?
  • inject a clock, no sleeps
  • ambulances from both roads?
  • queue them, serve in order
  • controller crashes?
  • hardware falls back to
  • flashing red

Say it like this

Here is the short version to say out loud. Each phase is a state that knows its lights, its duration, the phase after it, and how to react to walk and siren events. Green always goes to yellow, and every change of road passes through all red. An independent conflict monitor checks each change and falls back to flashing red. Time comes from an injected clock, so tests run instantly.

In the interview
  • "Each phase is a State that
  • knows its lights, duration,
  • next phase and how it reacts
  • to walk and siren events.
  • Green always goes to yellow,
  • every road change passes all
  • red, and a conflict monitor
  • checks each change. Time comes
  • from an injected clock."

Interview questions

Why use the State pattern for a traffic signal?

Each phase has different lights, a different duration, a different next phase and different reactions to events. As separate classes behind one Phase interface, adding a night mode or a turn arrow is a new class, and the controller just delegates to the current phase instead of growing a giant switch.

How do you guarantee two crossing roads never get green together?

By structure and by a check. Every phase lights at most one axis, green can only go to yellow, and every change of road passes through all red. On top of that, an independent conflict monitor validates every transition and enters flashing red if a rule is ever broken.

Why have an all-red phase at all?

A car that entered on yellow may still be in the middle of the junction when the light turns red. A short all-red gap lets it clear before the crossing road gets green, and it is also the natural decision point for walk and emergency requests.

How do you test timing logic without waiting?

Inject a clock. The controller stores a deadline and tick() compares it with clock.now(). Tests use a simulated clock and advance it in a loop, so hours of traffic run in milliseconds and every run is deterministic.

How is a pedestrian request handled?

Pressing the button sets a waiting flag and notifies the current phase. A green phase may end early, but not before its minimum green. When the next all-red phase ends it sees the flag, clears it and enters a walk phase with all cars stopped.

How does the emergency vehicle override work?

If the vehicle's road is already green, that phase becomes an emergency green held until cleared. Otherwise the crossing green ends after its minimum time and the normal yellow and all red follow, then all red gives the emergency road its green. Safety order is never skipped.

What happens if two emergency vehicles arrive from crossing roads?

They cannot both get green. Our controller serves the first and ignores the second until the first is cleared. A better version keeps a queue of requests: when the first clears, the normal yellow and all red run and the second road gets its emergency green next.

How do you make the controller thread safe?

Timer ticks, buttons and siren detectors can arrive on different threads, so all public controller methods are synchronized and every phase change goes through one private method. Another option is a single event-loop thread that reads events from a queue.

How would you coordinate many intersections?

Give each junction its own controller and let a central service push timing plans. For a green wave, offset each junction's cycle start by the travel time from the previous one, so cars moving at the target speed meet a string of greens.