什么时候Java线程活着? [英] When is a Java thread alive?

查看:236
本文介绍了什么时候Java线程活着?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是关于Java线程词汇的一个非常基本的问题。

This is a pretty basic question about the vocabulary of Java threads.

我看不到任何可能的重复,但可能有。

I can't see any possible duplicates but there might be.

这个词有什么用? 活着 参考Oracles文档?

What does the word alive refer to in Oracles documentation?

是否还没有完成 run()方法或其他任何参数?

Is it when the run() method has not yet completed or is it any other parameter?

推荐答案

根据您提到的Javadoc:

According to the Javadoc you mentionned:


如果一个线程已经启动并且尚未死亡,则该线程处于活动状态。

A thread is alive if it has been started and has not yet died.

一个线程在其<$ c $时启动 c> start()方法被调用并在 run()方法结束时死,或者调用stop()(现已弃用)。所以是的,当一个线程的 run()方法仍然在进行时,它仍处于活着状态,但它在<$ c的调用之间的时间窗口中也是活着的 $ c> start()以及JVM对 run()方法的隐式调用。

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.

您还可以查看 Thread.getState() 有关线程状态的有趣信息 @Marou Maroun建议。

You can also check the Thread.getState() and interesting information about Thread States suggested by @Marou Maroun.

我也关注他的建议警告您,如果抛出的异常被传播超出 run ,则Thread可以提前结束。在这种情况下,线程将不再存在。

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.

编辑:正如@zakkak所建议的那样,即使运行,线程也可以被认为是活动的()方法尚未启动。如果您想要对何时调用它进行适当的控制,请使用 ScheduledExecutorService ,特别是 schedule() 方法,为您提供更精确的执行计划。

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.

这篇关于什么时候Java线程活着?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆