在我的pong遊戲中,每個對象(球和兩個槳)都在獨立線程中運行。程序拋出IllegalThreadStateException
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
和遊戲沒有按不會繼續。 什麼問題?它不停止線程?
爲什麼需要使用三個獨立的線程? – 2013-02-10 12:36:16
因爲我想獨立控制所有對象。 – lapots 2013-02-10 12:40:11
如果你有200個遊戲對象,你會使用200個線程嗎?什麼阻止你從一個線程控制多個對象?也許我不明白「獨立控制所有對象」的含義。 – 2013-02-10 12:43:39