I have tried some sample code along the lines of:
Thread thread = new TestThread();
thread.start();
thread.isAlive();
It appears to me that the only way for the isAlive() call to return false, is for the thread to have already finished. Is this true?
The Java 7 JavaDoc for start:
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
The Java 7 JavaDoc for isAlive:
Tests if this thread is alive. A thread is alive if it has been started and has not yet died.
Neither of these seem very conclusive to me.
If you call start() method on Thread, Java Virtual Machine will call run() method and two threads will run concurrently now - Current Thread and Other Thread or Runnable implementation.
No, you can not directly call run method to start a thread. You need to call start method to create a new thread. If you call run method directly , it won't create a new thread and it will be in same stack as main.
start method of thread class is implemented as when it is called a new Thread is created and code inside run() method is executed in that new Thread. While if run method is executed directly than no new Thread is created and code inside run() will execute on current Thread and no multi-threading will take place.
start() method causes this thread to begin execution, the Java Virtual Machine calls the run method of this thread. The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
someThread.start()
will cause that thread to go into
runnable staterun
method immediately after start()
is called.someThread.start()
is called, the thread can move from runnable to runing state and even waiting state. Tests if this thread is alive. A thread is alive if it has been started and has not yet died.
This means, the thread is alive when its start()
is called and its run()
not completed yet. Completion of run()
method means thread is dead.
Thread has started doesn't mean it is already executing run method but it's status is Alive.
So after start is returned Thread is alive but not guaranteed to be executing run method it's state can be anything except New after completion of start method. (Runnable, Waiting, Terminated, etc)
t.isAlive() returns true if t is not in the NEW or TERMINATED state
Also take a look at this great resource on java threading
A thread t
is alive as soon as t.start()
returns and until t.run()
completes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With