30 January 2011

Java Threads - Why you can't start a thread twice?

Assume the following code
class Mythread extends Thread {
          }


          Mythead thread = new Mythread(); 
          thread.start(); thread.start();

Why you cannot start the thread (i.e calling thread.start()) twice? Why JVM panics when you do that?

6 comments:

Bala Vijay said...

If you want, create a new Thread object and start it. Thread has a lifecycle. Each thread is unique. Why do you want to start a Thread twice? It cant get birth twice. What is your opinion?

Lakshmi said...

@Bala Vijay

your answer is absolutely rocking :-).

Sandeep Kanabar said...

Say you make a journey from A to B. A journey done is gone. To again go from A to B, you've to start a new journey. Its like Once A human being dies and life ends, he can't re-start his life:-) - the JVM [Yamaraj] marks the Thread[human being] as DEAD. Makes me wonder if our Yamaraj too uses .start() method:-)

Bala Vijay said...

@lakshmi: Thanks Guruji :-)

Anonymous said...

in case of creating a thread and killing it and assigning back to another client requires of starting thread twice

Anonymous said...

@Sandy, Nice real life example...
Thanks and carry on...