Search⌘ K
AI Features

Solution: Multi-Player Game Lobby

Explore how to implement a multi-player game lobby that synchronizes player threads using the CyclicBarrier concurrency utility in Java. Understand simulating network latency, thread coordination, and ensuring all players enter the game simultaneously, enhancing your skills in managing concurrent tasks in modern Java applications.

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