终止线程复兴 [英] Terminated Thread Revival

查看:107
本文介绍了终止线程复兴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在arraylist中存储了一堆线程对象。我希望能够随机启动这些线程。同一个线程可以多次启动。在我开始一个线程对象之前,我检查线程是否处于活动状态,以及它们是否具有NEW或TERMINATED状态。这个限制因为,我不想打扰'忙'线程。现在,对于新线程,这很好用。但对于TERMINATED线程,我得到一个例外。

I am storing a bunch of threads objects in an arraylist. I want to be able to start these threads at random. Same thread can be started more than once. Before I start a thread object, I check on whether the thread is alive, and if they have either of NEW or TERMINATED status. This restriction because, I don't want to disturb the 'busy' threads. Now, for NEW threads, this works fine. But for TERMINATED thread, I get an exception.

线程结束时,它不应该回到'新'状态吗?或者线程是一次性的 - 就像使用一次并完成一样?

When a thread ends, shouldn't it go back to being 'new'? Or are threads 'disposable' - like use once and done?

推荐答案

正如它在 Thread.start(),它从不多次启动一个线程是不合法的。特别是,线程一旦完成执行就不会重新启动。

As it says in the documentation for Thread.start(), "It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution."

你最好保持一个状态 Runnable 实例并实现您自己的逻辑跟踪每一个的执行何时完成。使用 Executor 可能是最简单的运行Runnables的方法。

It is better for you to keep hold of Runnable instances and implement your own logic for keeping track of when the execution of each one of them finishes. Using an Executor is probably the simplest way to run the Runnables.

这篇关于终止线程复兴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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