简体   繁体   中英

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.

线程在 start() 返回后一直处于活动状态,直到 run() 返回到 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.

A thread is considered to be alive from the moment you create a Thread object and start it until it completes the run method or dies. It will be said to be in alive state even if it is in idle, running or sleep state.

Thread is "Alive" means that Thread is still running.

Yes, you can say that run() method is executing for the Alive Thread.

Moreover, isAlive() method is used to know if the Thread is still running.

final boolean isAlive()

The isAlive() method returns true if the thread upon which it is called is still running. It returns false otherwise.

一个线程在 New State 或 Running/Wait State 时是存活的。我们也可以知道,直到线程死亡,它在内存中都是存活的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM