gpt4 book ai didi

java - 线程未保持 Activity 状态 - IllegalStateException

转载 作者:行者123 更新时间:2023-12-02 07:26:19 26 4
gpt4 key购买 nike

这是我使用线程制作的一个小程序的片段。

JOptionPane.showMessageDialog(null, "Before: " + thread.isAlive());
if (!thread.isAlive()) {
JOptionPane.showMessageDialog(null, "Thread is not alive.");
thread.start();
}
JOptionPane.showMessageDialog(null, "After: " + thread.isAlive());

此代码可使用按钮激活。当我第一次按下按钮时,我正确地得到“之前:假”,然后是“之后:真”。当我再次按下按钮时,我错误地得到“Before: false”,然后是“After: true”,但期望 Before: true,因为我没有销毁线程或覆盖变量。

我相信这就是导致我收到 IllegalStateException 的原因(如果我也错了,请纠正我!)

谁能向我解释一下我做错了什么?

编辑:

public class SomeClass extends Applet
{

private ClassThatExtendsThread thread;

public void init()
{
super.init();

//Some UI elements are created here.

thread = new ClassThatExtendsThread (/*there are some parameters*/);
}

最佳答案

一旦线程完成运行,它就被认为是死亡的。此时在同一线程上调用 isAlive 将始终返回 false 结果。 JavaDoc for Thread确实提到了这一点:

public final boolean isAlive()Tests if this thread is alive. A thread is alive if it has been started and has notyet died.

If you are not re-instantiating your thread instance in-between calls to your code snippet then you will definitely get an IllegalStateException. This is because you attempt to start a thread that has already been terminated:

if (!thread.isAlive()) {
JOptionPane.showMessageDialog(null, "Thread is not alive.");
thread.start();
}

请注意,为了将来引用,您可以通过 getState 方法查询线程状态,这至少有助于分析错误。

关于java - 线程未保持 Activity 状态 - IllegalStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13550046/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com