I got an assignment for university where I have to implement a hangman game with Threads in Java. My problem is that I can't understand how to handle the threads. In my code there is a GameLeader who prompts the GuessingPlayer to enter a char which he guesses in the startWord. After he did that (run()-method) he takes the message further. The connection between the two players should be arranged with 'Messages' (own implemented class). It's working if I use run() instead of wait(). Can u help me to understand why the while loop is not working after the first entered message?
Thanks!
Class GameLeader:
public class GameLeader {
public static void main(String[] args) throws IOException {
GuessingPlayer guessingPlayer = new GuessingPlayer(userInterface);
String guess;
System.out.println("Please enter a startWord to begin!");
String startWord = userInterface.enterWord();
guessingPlayer.start();
while (attempts < 11) {
synchronized (guessingPlayer) {
System.out.println("It's your turn, Guessing Player!");
guessingPlayer.wait();
guess = guessingPlayer.message.toString();
if (startWord.contains(guess)) {
...
}
} else {
...
}
userInterface.mainMenu(guess);
}
}
}
}
Class GuessingPlayer:
public class GuessingPlayer extends Thread {
Message guessMessage;
private UserInterface userInterface;
GuessingPlayer(UserInterface userInterface) {
this.userInterface = userInterface;
}
@Override
public void run() {
synchronized (this) {
guessMessage = new Message(userInterface.enterWord());
notify();
}
}
}