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?
Use Thread. currentThread(). isAlive() to see if the thread is alive[output should be true] which means thread is still running the code inside the run() method or use Thread.
isAlive() method of Thread Class in Java programming The isAlive function − It is used to check if a thread is alive or not. Alive refers to a thread that has begun but not been terminated yet. When the run method is called, the thread operates for a specific period of time after which it stops executing.
Java Thread isAlive() method The isAlive() method of thread class tests if the thread is alive. A thread is considered alive when the start() method of thread class has been called and the thread is not yet dead. This method returns true if the thread is still running and not finished.
In java, isAlive() and join() are two different methods that are used to check whether a thread has finished its execution or not. The isAlive() method returns true if the thread upon which it is called is still running otherwise it returns false. But, join() method is used more commonly than isAlive().
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.
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