当前位置: 动力学知识库 > 问答 > 编程问答 >

java - program throws IllegalThreadStateException

问题描述:

In my pong game every object(ball and two paddles) is running in the independent thread.

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();

}

I want to set game on pause when I press ESC and when I press ESC again - continue game. So in keyPressed event I've done like this

 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();

}

}

To continue game - I restart all threads but set parameters for the objects from previous game state

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();

}

But program throws IllegalThreadStateException and the game doesn't continue.

What's the problem? It doesn't stop threads?

网友答案:

To continue game - I restart all threads ...

You cannot restart a Java thread. The javadoc for Thread.start() states this:

" 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."

You need to either create new thread objects and start them, or figure out some way to tell the existing threads to enter an application-defined "paused" state when they are interrupted, and wait there until they are told to "resume".

网友答案:

You cannot restart a thread after it was stopped/interrupted. But nothing stops you from creating a new thread and starting it.

A SO answer that lists some options you could use

网友答案:

Threads are not allowed to be started again after being terminated. From the documentation:

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

Creating a new instance of the thread and starting it is legal. However, this won't achieve the "pause" effect, unless you make sure the state provided to the new thread represents accurately the paused state.

分享给朋友:
您可能感兴趣的文章:
随机阅读: