Reputation: 711
I have a Thread which runs my game loop. I want to be able to run this game loop each time I start a new game. But since the threads in Java can only be started once, how can I do this?
Upvotes: 1
Views: 1384
Reputation: 33534
1. When you say that "you need to run a thread"
, i means you want to start a sub-task on a separate thread.
2. Now if you mean this certain sub-task, then please prefer to run a new thread
.
3. As you said But since the threads in Java can only be started once
This means that when a thread (thread of execution)
completes its run()
method, then the Thread object associated with it permanently looses its threadness, right....
But if this thread is from a pool, then the pool itself manages the Thread objects and its reused. Try using Executors
from java.util.concurrent
package.
Upvotes: 2
Reputation: 121649
1) The short answer is precisely what SLaks already said: just "...create a new thread around the same runnable instance and start that."
2) I think you might be confused about the distinction between the everyday meaning of "start", and the semantics of the Java Thread method "start()". This tutorial might help:
3) Should you wish to re-use the same thread, you can use the methods "wait()" and "resume()":
Upvotes: 0
Reputation: 718788
Since you want the Thread that runs the game loop to keep running it, you need to code it something like this:
public class GameLoop implements Runnable {
...
public void run() {
while (gameNotFinished) {
// do stuff
}
}
}
If that is not working, then the chances are that the run()
method is dying because of an exception that you are not catching / logging, and therefore not noticing.
Upvotes: 2
Reputation: 887405
Create a new Thread
around the same Runnable
instance and start that.
Upvotes: 3