在同一个线程上调用start方法两次是否合法?

Wil*_*ill 88 java multithreading android

以下代码导致java.lang.IllegalThreadStateException: Thread already started我在程序中第二次调用start()方法.

updateUI.join();    

if (!updateUI.isAlive()) 
    updateUI.start();
Run Code Online (Sandbox Code Playgroud)

第二updateUI.start()调用就会发生这种情况.我已经多次执行它并且调用线程并且在击中之前完成运行完成updateUI.start().

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

线程只能启动一次吗?如果我想再次运行该线程怎么办?这个特定的线程在后台进行一些计算,如果我不在线程中执行它而不是在UI线程中完成,并且用户有一个不合理的漫长等待.

coo*_*ird 109

Java的API规范Thread.start方法:

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

此外:

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

所以,是的,Thread只能开始一次.

如果我想再次运行该线程怎么办?

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


Bob*_*oss 13

非常正确. 从文档:

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

就重复计算可以做什么而言,似乎可以使用SwingUtilities invokeLater方法.您已经在尝试run()直接调用,这意味着您已经在考虑使用Runnable而不是原始的Thread.尝试invokeLaterRunnable任务上使用该方法,看看它是否更适合您的心理模式.

以下是文档中的示例:

 Runnable doHelloWorld = new Runnable() {
     public void run() {
         // Put your UI update computations in here.
         // BTW - remember to restrict Swing calls to the AWT Event thread.
         System.out.println("Hello World on " + Thread.currentThread());
     }
 };

 SwingUtilities.invokeLater(doHelloWorld);
 System.out.println("This might well be displayed before the other message.");
Run Code Online (Sandbox Code Playgroud)

如果println用计算替换该调用,它可能正是您所需要的.

编辑:跟进评论,我没有注意到原帖中的Android标记.相当于Android工作中的invokeLater Handler.post(Runnable).从它的javadoc:

/**
 * Causes the Runnable r to be added to the message queue.
 * The runnable will be run on the thread to which this handler is
 * attached.
 *
 * @param r The Runnable that will be executed.
 *
 * @return Returns true if the Runnable was successfully placed in to the
 *         message queue.  Returns false on failure, usually because the
 *         looper processing the message queue is exiting.
 */
Run Code Online (Sandbox Code Playgroud)

因此,在Android世界中,您可以使用与上面相同的示例,将Swingutilities.invokeLater相应的帖子替换为a Handler.