问题描述
我使用以下code时获得 IllegalThreadStateException
例外:
我已经开始这个线程一次(使用 thread.start()
),并再次试图在其他地方开始,所以下面用code:
I am getting IllegalThreadStateException
exception when using following code:I have already started this thread once(by using thread.start()
) and again trying to start it at another place, so used following code:
thread.interrupt();
thread.start();
但 thread.start()
抛出 IllegalThreadStateException
。
我应该使用什么来解决呢?
What should I use to solve it?
推荐答案
发
对象只是为了启动一次。如果你需要停止/中断发
,然后想再次启动它,你应该创建一个新的实例,并调用开始()
就可以了:
Thread
objects are only meant to be started once. If you need to stop/interrupt a Thread
, and then want to start it again, you should create a new instance, and call start()
on it:
thread.interrupt(); // if you need to make sure thread's run() method stops ASAP
thread = new MyThreadSubclass();
thread.start();
IllegalThreadStateException - 如果线程已经启动
我知道这不是100%的清楚,你不能叫开始()
再次,即使你previously名为中断( )
,但这是它的工作方式。
I know it's not 100% clear that you can't call start()
again, even if you previously called interrupt()
, but that's the way it works.
如果你看一下,这个问题更加清晰。
If you look at the API docs for standard Java, this issue is more clear.
这篇关于停止线并重新启动黑莓给人IllegalThreadStateException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!