gpt4 book ai didi

java - 程序抛出 IllegalThreadStateException

转载 作者:行者123 更新时间:2023-12-01 07:33:54 25 4
gpt4 key购买 nike

在我的乒乓球游戏中,每个对象(球和两个 Racket )都在独立线程中运行。

static Ball b = new Ball(195, 145);

Thread ball = new Thread(b);
Thread paddle1 = new Thread(b.paddle1);
Thread paddle2 = new Thread(b.paddle2);
public void startGame(){
gameStarted = true;
ball.start();
paddle1.start();
paddle2.start();
}

我想在按下 ESC 时将游戏设置为暂停,并在再次按下 ESC 时设置游戏 - 继续游戏。所以在 keyPressed 事件中我这样做了

 if (e.getKeyCode() == KeyEvent.VK_ESCAPE){
if (gameStarted) {
gameStarted = false;
ballCurrentX = b.x; //save all states
ballCurrentY = b.y;
ballXDirection = b.xDirection;
ballYDirection = b.yDirection;
p1Score = b.p1Score;
p2Score = b.p2Score;
p1CurrentY = b.paddle1.y;
p2CurrentY = b.paddle2.y;
try {
ball.interrupt();
ball.join();
paddle1.interrupt();
paddle1.join();
paddle2.interrupt();
paddle2.join();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
else {
gameStarted = true;
continueGame();
}
}

要继续游戏 - 我重新启动所有线程,但为之前游戏状态的对象设置参数

public void continueGame(){
gameStarted = true;
b = new Ball(ballCurrentX, ballCurrentY);
b.xDirection = ballXDirection;
b.yDirection = ballYDirection;
b.p1Score = p1Score;
b.p2Score = p2Score;
b.paddle1.y = p1CurrentY;
b.paddle2.y = p2CurrentY;
ball.start();
paddle1.start();
paddle2.start();
}

但是程序抛出IllegalThreadStateException并且游戏无法继续。有什么问题?它不会停止线程?

最佳答案

To continue game - I restart all threads ...

您无法重新启动 Java 线程。 Thread.start() 的 javadoc声明如下:

" It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution."

"Throws: IllegalThreadStateException - if the thread was already started."

您需要创建新的线程对象并启动它们,或者找出某种方法来告诉现有线程在中断时进入应用程序定义的“暂停”状态,并在那里等待,直到被告知“恢复” ”。

关于java - 程序抛出 IllegalThreadStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14797747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com