I want to restart a thread for some use, for example in the below code.
class Ex13 implements Runnable {
int i = 0;
public void run() {
System.out.println("Running " + ++i);
}
public static void main(String[] args) throws Exception {
Thread th1 = new Thread(new Ex13(), "th1");
th1.start();
//th1.join()
Thread th2 = new Thread(th1);
th2.start();
}
}
When I’m executing the above program , some time i’m getting the output as
Running 1
Running 2
and some time i’m getting only
Running 1
After few run i’m getting only
Running 1 as output.
I’m totally surprise about this behavior. Can any one help me understand this.
if I put the join() then i’m getting only Running 1.
You reuse
Threadinstance, notRunnable. Thread overwrites itsrun()method toWhere target is the
Runnablethat you give to the constructor. besides that,Threadhas anexit()method that is called by the VM, and this method sets target to null (the reason is this bug). So if your first thread has the chance to finish its execution, itsrun()method is pretty much empty. Addingth1.join()proves it.If you want to keep some state, you need to keep reference to your
Runnableinstance, not theThread. This wayrun()method will not be altered.