How to implement a java thread using monitors?

Viewed 124

Consider the following controller class in a turn-based, multi-player game. The user interface, which runs in a separate thread, will pass Player and GameMove objects to GameEngine’s thread each time one of the players makes a move.

1 public class GameEngine
2 {
3    private GameWorld world;
4
5    public GameEngine(GameWorld world)
6    {
7     this.world = world;
8    }
9
10    public void startGame()
11    {
12       Runnable task = new Runnable()
13      {
14         @Override
15        public void run()
16       {
17          try
18          {
19            while(true)
20            {
21              Player player = ... // Get current player
22              GameMove move = ... // Get move made by player
23              world.update(player, move);
24            }
25           }
26          catch(InterruptedException ex)
27       {

28       }
29    }
30   });
31   new Thread(task).start();
32  }
33 }

Using a monitor, implement a communication mechanism, inside GameEngine, that allows the UI to pass the required information to GameEngine, as indicated in the comments. You may need to add extra fields and/or methods

For the above question, I wrote the following code snippet.

public class GameEngine
{
    private Object monitor = new Object();
    private GameWorld world;
    private boolean flag = false;

    public GameEngine(GameWorld world)
    {
        synchronized(monitor)
        {
            if(flag)
            {
                monitor.wait();
            }

            this.world = world;
            flag = true;
            monitor.notify();
        }
    }

    public void startGame()
    {
        Runnable task = new Runnable()
        {
         public void run()
         {
            try
            {
                while(true)
                {
                    synchronized(monitor)
                    {
                        if(!flag)
                        {
                            monitor.wait();
                        }
                    }
                    Player player = ...
                    GameMove move = ...
                    World.update(player,move);
                    flag = false;
                    monitor.notify();
                }
            }
            catch (InterruptedException ex)
            {

            }
         }
        };
        new Thread(task).start();
    }
}

Can someone please check that whether my answer is correct or not?

0 Answers
Related