为什么在此方法中使用thread.sleep?

时间:2018-11-29 21:57:15

标签: java multithreading

我正在关注有关https://proghammer.wordpress.com/2010/11/25/chess07-new-game-flow-handling/的教程

我不理解在waitForMove()方法中使用Thread.sleep 我将时间更改为0,但仍然可以正常使用,但是如果我将其删除 感觉游戏在某种状态下处于冻结状态,为什么需要它?

谢谢

public class ChessGame implements Runnable{

       //..

    @Override
    public void run() {
        this.startGame();
    }

    /**
     * start main game flow
     */
    public void startGame(){
        // check if all players are ready
        System.out.println("ChessGame: waiting for players");
        while (this.blackPlayerHandler == null || this.whitePlayerHandler == null){
            // players are still missing
            try {Thread.sleep(1000);} catch (InterruptedException e) {}
        }

        // set start player
        this.activePlayerHandler = this.whitePlayerHandler;

        // start game flow
        System.out.println("ChessGame: starting game flow");
        while(!isGameEndConditionReached()){
            waitForMove();
            swapActivePlayer();
        }

        System.out.println("ChessGame: game ended");
    }

    /**
     * wait for a valid player move and execute it
     */
    private void waitForMove() {
        Move move = null;
        // wait for a valid move
        do{
            move = this.activePlayerHandler.getMove();
            try {Thread.sleep(100);} catch (InterruptedException e) {}
        }while(move == null || !this.moveValidator.isMoveValid(move,false));

        //execute move
        boolean success = this.movePiece(move);
        if(success){
            this.blackPlayerHandler.moveSuccessfullyExecuted(move);
            this.whitePlayerHandler.moveSuccessfullyExecuted(move);
        }else{
            throw new IllegalStateException("move was valid, but failed to execute it");
        }
    }
}

0 个答案:

没有答案