Java 游戏服务器线程安全接收 websocket 消息

Java Game Server thread-safe recieving web-socket messages

我正在将我的 python websocket 游戏服务器升级到 Java,(使用 Jetty 进行 websockets),最近开始学习线程安全。

我的挑战是,游戏逻辑(gameRoom 实例)在主线程上运行,但服务器将接收玩家消息(例如加入游戏室的消息),并从另一个线程通知游戏逻辑。我最初(在 python-当所有内容都在主线程上时)只是立即处理消息,(例如,在收到消息时添加一个播放器)。这可能会导致多线程出现问题,因为 gameRoom 线程可能同时将玩家添加到玩家数组。 (玩家列表最终在添加玩家时被共享=不是线程安全的!)

在它自己的线程上处理从 servlet 运行 接收消息并在不弄乱主线程上的游戏 运行 的情况下处理这些消息的最简单方法是什么(不同的线程)?在我的脑海中,我会想象某种单向缓冲区(例如 http://web.mit.edu/6.005/www/fa14/classes/20-queues-locks/message-passing/)在部分逻辑期间将新消息排队,仅由 gameRoom 本身处理。或者有没有办法完全避免多线程!? *请给出你的想法,我很想听听那些比我的线程知识水平更高的人的意见。我非常感谢所有提示/建议:) *

我花时间做了一个简单的例子来说明发生了什么(请忽略 synax 错误,为了方便起见,我把它写得很短 :)):

class ServerClass {
    static GameRoomClass gameRoom;


    static void main() {
        //psuedocode start Jetty Server, this server runs in another thread, will call onServerMessage()
        jettyServer.start();
        jettyServer.onMessageCallback=(onServerMessage); //set message callback (pseudocode)

        //create game room, run on main thread
        gameRoom = GameRoomClass();
        gameRoom.runGameRoom();
    }

    //when the server gets a message from a player,
    //this will be called by the server from another thread, will affect the GameRoom
    static void onServerMessage(Message theMessage) {
        gameRoom.gotServerMessage();
    }
}

//this runs game logic
class GameRoomClass {
    ArrayList<E> players = new ArrayList<>();

    public void runGameRoom() {
        while (true) {
            //move players, run logic...

            //sometimes, may call addNewPlayer AS WELL
            if(...){
                addNewPlayer();
            }
        }

    }

    public gotServerMessage(){
        //this will only be called by the 'Server' thread, but will enter 'addNewPlayer' method
        //meaning it will access shared value players?
        addNewPlayer()
    }

    public addNewPlayer(){
        //this will be called by the server thread, on getting a message
        //can ALSO be called by gameRoom itself
        players.add(new PlayerObj());
    }

}

class PlayerObj {
    //a player in the game
}

最简单有效的方法是使用 java.util.concurrent 包中的线程安全集合 类 之一。 对于给定的情况,ConcurrentLinkedQueue 似乎是一个好的开始。