When is a Java thread alive?
This is a pretty basic question about the vocabulary of Java threads.
I can't see any possible duplicates but there might be.
What does the word alive refer to in Oracles documentation?
Is it when the run()
method has not yet completed or is it any other parameter?
According to the Javadoc you mentionned:
A thread is alive if it has been started and has not yet died.
A thread "starts" when its start()
method is invoked and "dies" at the end of its run()
method, or when stop()
(now deprecated) is invoked. So yes, a thread is "alive" when its run()
method is still ongoing, but it is also "alive" in the time window between the invocation of start()
and the implicit invocation of the run()
method by the JVM.
You can also check the Thread.getState()
and interesting information about Thread States suggested by @Marou Maroun.
I am also following his suggestion warning you that a Thread can end prematurely in case an Exception is thrown that propagates beyond run
. The Thread would not be alive anymore in that case.
EDIT: As suggested by @zakkak, the thread can be considered alive even though the run()
method did not start yet. In case you want to have proper control on when it will be invoked, use the ScheduledExecutorService
, specifically the schedule()
method which gives you more precise execution schedule.
Thread is alive after start() returned and until run() returns to JVM.
A thread is alive when it is in new/Running/wait state. In essence the run method can be running or not
A thread is alive when the start
method is called on it and before it is dead. It can move to waiting state number of times before it is dead, even if it is in the waiting state it is still alive.
From being alive to being dead, it can move from runnable
state to waiting
state.