Search⌘ K
AI Features

Solution: Multi-Player Game Lobby

Explore how to manage concurrent player connections and synchronize thread execution using Java's CyclicBarrier in a multiplayer game lobby. Understand how to simulate network delays, block threads until all players are ready, and execute a coordinated start action to ensure all players enter the match simultaneously.

We'll cover the following...
Java 25
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class GameLobby {
static class Player implements Runnable {
private final String name;
private final CyclicBarrier barrier;
public Player(String name, CyclicBarrier barrier) {
this.name = name;
this.barrier = barrier;
}
@Override
public void run() {
try {
System.out.println(name + " is joining...");
// Simulate varying connection speeds (500ms to 2000ms)
long delay = (long)(Math.random() * 1500) + 500;
Thread.sleep(delay);
System.out.println(name + " is waiting in the lobby...");
// 3. Wait for all 4 players to reach this point
barrier.await();
// 4. Proceed together
System.out.println(name + " has entered the match!");
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
int totalPlayers = 4;
System.out.println("Lobby is open. Waiting for " + totalPlayers + " players...");
// 1. Create the barrier with a barrier action
CyclicBarrier barrier = new CyclicBarrier(totalPlayers, () -> {
System.out.println("\n*** All players are present! Game starting now! ***\n");
});
// 2. Start the player threads
for (int i = 1; i <= totalPlayers; i++) {
new Thread(new Player("Player " + i, barrier)).start();
}
}
}
...