重新启动while循环

时间:2012-07-11 16:45:30

标签: java

我正在尝试重启while循环。我已经声明了boolean类型的变量keepGoing。如果int变量x不在窗口中,则将change更改为false。然后reset()方法必须keepGoing = true。它工作但while循环不起作用。

带有reset()和checkWin()的类:

private void reset() {
    b.x = 250;
    b.y = 100;
    b.keepRunning = true;
    a.keepGoing = true;
    System.out.println(a.keepGoing);
}

public void checkWin() {
    if (b.keepRunning) {
        if (b.getX() < -10) {
            a.score++;

            JOptionPane.showMessageDialog(okno, "Player " + p.getScore()
                    + " - Computer " + a.getScore(), "Oh, well...",
                    JOptionPane.INFORMATION_MESSAGE);
            b.keepRunning = false;
            a.keepGoing = false;
            System.out.println(a.keepGoing);
            reset();
        } else if (b.getX() > 599) {
            p.score++;
            JOptionPane.showMessageDialog(okno, "Player " + p.getScore()
                    + " - Computer " + a.getScore(), "Good!",
                    JOptionPane.INFORMATION_MESSAGE);
            b.keepRunning = false;
            a.keepGoing = false;
            System.out.println(a.keepGoing);
            reset();
        }
    }
}

第二课有线程,keepGoing和while循环:

Runnable intel = new Runnable() {
    public void run() {
        while (keepGoing) {
            while (getY() < board.ball.getY()) {
                System.out.println(keepGoing + " " + getY());
                try {
                    if (y == 220) {
                    } else {
                        y += 1;
                        Thread.sleep(10);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            while (getY() > board.ball.getY()) {
                System.out.println(keepGoing + " " + getY());
                try {
                    if (y == 0) {
                    } else {
                        y -= 1;
                        Thread.sleep(10);
                    }
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
};

2 个答案:

答案 0 :(得分:10)

使用关键字continue转到循环的下一次迭代。例如:

while(true)
{
   // ...

   if(!condition) continue; // this will go to the beginning of the while loop.

   // ...
}

答案 1 :(得分:1)

如果从不同的线程访问keepGoing标志(我认为您的示例正在显示,它不清楚),那么您需要使用同步来确保在更新keepGoing标志时reset()方法,它对runnable中的线程可见。您可能想查看AtomicBoolean课程。

参见Effective Java,Item#66