如何使用监视器实现Java线程?

时间:2018-09-09 20:02:24

标签: java monitor java-threads

在基于回合的多人游戏中考虑以下控制器类。用户 接口在单独的线程中运行,会将Player和GameMove对象传递给 每次一名玩家移动时,GameEngine的线程。

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 }

使用监视器,在GameEngine内部实现通信机制, 允许UI将所需信息传递给GameEngine,如所示 在评论中。您可能需要添加其他字段和/或方法

对于上述问题,我编写了以下代码段。

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

有人可以检查我的答案是否正确吗?

0 个答案:

没有答案