Question

I'm having a few problems with my game I'm creating. I'm trying to implement a turn structure, however I cannot seem to get a class to wait until another class has finished.

The main Game class needs to wait until the user presses a button in the GameView class before proceeding to calculate what has happened then call the turn method again.

I have tried using the wait() and notify() methods however the GameView GUI doesn't load or it will not notify the Game class to proceed. Can anyone help? Thanks

if (player1.isPlayerFinsihed() == false && player1.getPlayersTurn() == true) {
            //Check for if the game has just been started
            if (player1.getDifficulty() == 0) {
                player1.setDifficulty(currentDifficulty);
                turn();
            }
            else {
                int number = questionArray1.getNumber(player1.getDifficulty());
                int playerCategory = player1.getCategory();
                int playerQuestionNumber = player1.getQuestionNumber();
                Question newQuestion = questionArray1.getQuestion(number,playerCategory);
                Answer newAnswer = questionArray1.getAnswer(number,playerCategory);
                GameView newGameView = new GameView(number, playerQuestionNumber, 1, newQuestion, newAnswer);

                //INSERT WAIT METHOD HERE

                if (newGameView.getCorrect() == true) {
                    //add score based on question position
                    System.out.println("Correct");
                }
                //False
                else {
                    //finish game for player
                    player1.setGameOver(true);
                }
                //display and wait
                //while (//main screen is not returning that the player is done) {
                //  do nothing
                //}
                turn();
            }
    }
Était-ce utile?

La solution

Use the Thread#join() method.

See a tutorial here:

http://www.tutorialspoint.com/java/lang/thread_join.htm

Autres conseils

As Sotirios Delimanolis pointed out in his comment, a class doesn't wait, neither run. A class is a piece of code and data, and as such, has no concept of execution. What executes code is a thread. Threads are independent and run code in parallel (at the same time). As such they have several mechanisms to allow synchronization between them. So if you want 2 classes to be executed at the same time, you need to spawn one thread for each. Then you just handle one of the threads to wait for the other to finish using Thread#join().

You can check the official tutorials to learn more about concurrency in Java.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top