#java #multithreading #sockets
Вопрос:
От GameServer.java:
while (true) { Socket clientSocket = serverSocket.accept(); PlayerThread playerThread = new PlayerThread(clientSocket, this); playerThreads.add(playerThread); playerThread.start(); if (playerThreads.size() == maxPlayers) { broadcast("All players have joined! Let the game begin!", null); } }
От PlayerThread.java:
@Override public void run() { try { BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); out.println("What's your name? "); String userName = in.readLine(); Player player = new Player(userName); gameServer.addPlayer(p); String clientMove; while ((clientMove = in.readLine()) != null) { gameServer.makeMove(player, clientMove); gameServer.broadcast(p.getName() " made the move: " clientMove, this); } } catch (IOException e) { e.printStackTrace(); } }
Запуск сервера:
Клиент1 в конце:
Клиент2 в конце:
Как мне дождаться, пока последний клиент (здесь, client2) введет свое имя, прежде чем передавать сообщение?
Вот функция трансляции:
public void broadcast(String message, PlayerThread excluded) { for (PlayerThread p : playerThreads) { if (p != excluded) p.sendMessage(message); } }
Ответ №1:
Воспользуйся CountDownLatch
:
private CountDownLatch countDownLatch = new CountDownLatch(maxPlayers);
Итак, после playerThreads.size() == maxPlayers
того, как вы достигли, позвоните await
:
if (playerThreads.size() == maxPlayers) { countDownLatch.await(); broadcast("All players have joined! Let the game begin!", null); }
Вам нужно передать это CountDownLatch
каждому PlayThread
, а после username
прочтения позвоните CountDownLatch#countDown
:
public PlayerThread(Socket socket, GameServer gameServer, CountDownLatch countDownLatch) throws IOException { downLatch = countDownLatch; } @Override public void run() { try { BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); out.println("What's your name? "); String userName = in.readLine(); downLatch.countDown(); } catch (IOException e) { e.printStackTrace(); } }