Trying to understand interthread communication with multiple objects

Viewed 55

I'll first give some context about my little program and then I'll elaborate my question.

Context:
I have a program that allows cars to cross a bridge from either left or right, however, the bridge is so tiny that only one car at the time is able to cross the bridge. Now, in order prevent crashes I implemented a Controller class, which ensures only one car is crossing the bridge at the time.

public class BridgeController {

    private boolean isBridgeOccupied = false;

    public synchronized void enterLeft() {
        try {
            while (isBridgeOccupied) {
                wait();
            }
            isBridgeOccupied = true;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized void enterRight() {
        try {
            while (isBridgeOccupied) {
                wait();
            }
            isBridgeOccupied = true;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized void leaveLeft() {
        isBridgeOccupied = false;
        notifyAll();
    }

    public synchronized void leaveRight() {
        isBridgeOccupied = false;
        notifyAll();
    }
}

Question:
Say there are 1_000_000 cars waiting on either side of the bridge. If I understand my implementation correctly the order of cars, at which they cross the road, should be random. After I executed the program to see how it works I realized that the crossing happens iterative.

R/L display whether a car enters the bridge from Right or Left
Expectation: RRLLRLRLLLLRLRLLLRLRRRRRRRL <- R/L are random
Observation: RLRLRLRLRLRLRLRLRLRLRLRLRLR <- iterative

Can someone explain me and maybe elaborate on why my code is behaving that way?

0 Answers
Related