I guess you extended the Thread
class and you have overridden the run
method. If you do this you are tying the runnable code to the Thread
's lifecycle. Since a Thread
can not be restarted you have to create a new Thread
everytime. A better practice is to separate the code to run in a thread from a Thread
's lifecycle by using the Runnable
interface.
Just extract the run
method in a class that implements Runnable
. Then you can easily restart it.
For example:
public class SomeRunnable implements Runnable {
public void run(){
... your code here
}
}
SomeRunnable someRunnable = new SomeRunnable();
Thread thread = new Thread(someRunnable);
thread.start();
thread.join(); // wait for run to end
// restart the runnable
thread = new Thread(someRunnable);
thread.start();
This practice makes it also easy if you need to remember the previous run state.
public class SomeRunnable implements Runnable {
private int runs = 0;
public void run(){
runs++;
System.out.println("Run " + runs + " started");
}
}
PS: Use a java.util.concurrent.Executor
to execute Runnable
s. This will decouple thread management from execution.
Executor executor = Executors.newSingleThreadExecutor();
...
SomeRunnable someRunnable = new SomeRunnable();
executor.execute(someRunnable);
Take a look at Executor Interfaces