在我的乒乓球比赛中,每个对象(球和两个球拍)都在独立线程中运行。
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
,游戏无法继续。有什么问题?它不会停止线程吗?