如何获取线程的状态?
这就是我定义线程的方式
public class Countdown implements Runnable{
public Countdown(){
new Thread(this).start();
}
//...
}
如果线程以这种方式启动,是否仍然可以获得线程的状态?喜欢
Countdown cd = new Countdown();
cd.getState();
this is how I define my thread
public class Countdown implements Runnable{
public Countdown(){
new Thread(this).start();
}
//...
}
Is it still possible to get the state of a thread if it is started that way? Like
Countdown cd = new Countdown();
cd.getState();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,事实并非如此。
如果你想能够获取状态,你必须保留对线程的引用;例如
,顺便说一句,还有其他原因导致这不是一个很好的模式:
如果对
Countdown
对象的引用丢失(例如,由于构造父对象期间出现异常),您将泄漏一个线程。线程和线程创建会消耗大量资源。如果有很多这样的 Countdown 对象,或者它们的生命周期很短,那么最好使用线程池。
No. It is not.
If you want to be able to get the state, you have to keep a reference to the Thread; e.g.
By the way, there are other reasons why this is not a great pattern:
If the reference to the
Countdown
object is lost (e.g. because of an exception during construction of the parent object), you will leak a Thread.Threads and thread creation consume a lot of resources. If there are a lot of these
Countdown
objects, or if they have a short lifetime, then you'd be better of using a thread pool.你可以做
You can do
由于它仅实现 Runnable,因此您必须提供一个包装方法来获取状态:
Since it's only implementing
Runnable
you'll have to provider a wrapper method to get the state:我建议使用 run() 方法并在那里分配正在运行的线程,而不是在 c-tor 中。
一些顺理成章的事情。
}
I'd recommend using the run() method and assign the running thread there, no in the c-tor.
Something along the lines.
}
抱歉,您永远不应该从构造函数启动线程。那个构造函数正在自找麻烦。进行更改,以便 Countdown 的实例化器正在创建线程。
Sorry to say, but you should never start a thread from the constructor. That constuctor is begging for problems. Change so that the instantiator of Countdown is creating the thread.