是合法的调用start方法两次在同一个主题?两次、方法、主题、在同一个

2023-09-11 20:30:15 作者:念你如初

下面code会导致java.lang.IllegalThreadStateException:线程已经开始。在第二的时间它是通过对程序运行。

The following code leads to "java.lang.IllegalThreadStateException: Thread already started." the second time it is run through on the program.

updateUI.join();    

if (!updateUI.isAlive()) 
    updateUI.start();

这发生在第二 updateUI.start()被调用时。我已经通过它多次加强和线程调用,并完全地运行到完成击球前 updateUI.start()

This happens the second time updateUI.start() is called. I've stepped through it multiple times and the thread is called and completly runs to completion before hitting updateUI.start().

调用 updateUI.run()避免了错误,但导致在UI线程中运行的线程(调用线程,正如在其他职位上的SO),这是不是我想要的。

Calling updateUI.run() avoids the error but causes the thread to run in the UI thread (the calling thread, as mentioned in other posts on SO), which is not what I want.

可以一个线程中的开始的只有一次?如果是的话比我该怎么办,如果我想再次运行线程?这种特殊的线程做一些计算的背景下,如果我不这样做的线程比它在UI线程完成,用户有不合理漫长的等待。

Can a Thread be started only once? If so than what do I do if I want to run the thread again? This particular thread is doing some calculation in the background, if I don't do it in the thread than it's done in the UI thread and the user has an unreasonably long wait.

推荐答案

从的Java API规范的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.

此外:

抛出:       IllegalThreadStateException - 如果已经启动该线程

Throws: IllegalThreadStateException - if the thread was already started.

所以,是的,一个只能启动一次。

So yes, a Thread can only be started once.

如果这样比我该怎么办,如果我想   再次运行线程?

一个线程两次调用start 方法会出现什么情况

If so than what do I do if I want to run the thread again?

如果一个需要运行一次以上,则应该让主题的一个新实例和呼叫启动就可以了。

If a Thread needs to be run more than once, then one should make an new instance of the Thread and call start on it.