在这种情况下如何防止方法两次运行?

时间:2018-07-11 12:55:20

标签: java multithreading methods

这是我拥有的代码的简化版本

Thread t = new Thread() {
    Scanner user = new Scanner(System.in);
    public void run() {
        setDistance();
    }

    void setDistance() {
        System.out.print("Set distance.");
        int distance = user.nextInt();
        if (distance < ableJump) {
            jump(); 
        } else { // if you are too weak to jump that far
            System.out.print("Too far!");
            setDistance();
        }
        // after that:
        if (player == 1) {
            player = 2; // sets to 2 if it was player 1's turn
        } else if (player == 2) {
            player = 1; // sets to 1 if it was player 2's turn
        }
        System.out.printf("Player %d's turn", player);
        /* now a method runs the threads again
         * and the cycle continues..
         */
    }
};

如果distance用户设置太大,从而触发了“太远” else语句,并且再次调用了该方法,则用户将获得新的机会来设置distance值。

但是问题是:setDistance()结束后,它返回到它被调用的位置,该位置也在setDistance()中,并从那里继续运行。这意味着方法setDistance()被运行两次,因此player变量切换回其原始状态。而且永远不会是玩家2的回合!

是否有其他替代方法可以执行此操作,但结果相同。

1 个答案:

答案 0 :(得分:2)

尝试执行一段时间,而不用调用函数。

void setDistance() {
    int distance;
    while (true) {
        System.out.print("Set distance.");
        distance = user.nextInt();
        if (distance < ableJump) {
            break;
        }
        System.out.print("Too far!");
    }
    jump(); 
    // after that:
    player = 3 - player;
    System.out.printf("Player %d's turn", player);
}