在同一个线程上两次调用 start 方法是否合法? [英] Is it legal to call the start method twice on the same Thread?

查看:36
本文介绍了在同一个线程上两次调用 start 方法是否合法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在程序中调用start()方法第二次时,以下代码导致java.lang.IllegalThreadStateException:线程已经启动.

The following code leads to java.lang.IllegalThreadStateException: Thread already started when I called start() method second time in 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 规范code>Thread.start 方法:

From the Java API Specification for the Thread.start method:

启动线程永远是不合法的不止一次.特别是,一个一旦线程可能不会重新启动已完成执行.

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.

是的,一个 Thread 只能启动一次.

So yes, a Thread can only be started once.

如果是的话,我该怎么做再次运行线程?

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

如果一个Thread需要运行多次,那么应该创建一个Thread的新实例并在其上调用start.

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.

这篇关于在同一个线程上两次调用 start 方法是否合法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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