Here is a snippet from a little program I am making using threads.
JOptionPane.showMessageDialog(null, "Before: " + thread.isAlive());
if (!thread.isAlive()) {
JOptionPane.showMessageDialog(null, "Thread is not alive.");
thread.start();
}
JOptionPane.showMessageDialog(null, "After: " + thread.isAlive());
This code is activated using a button. When I press the button the first time, I correctly get “Before: false” and then “After: true”.
When I press the button again, I incorrectly get “Before: false” and then “After: true”, but expect Before: true, since I am not destroying the thread or overriding the variable.
I believe that this is what is causing IllegalStateException which I am getting (correct me if I am wrong on that too!)
Can anyone explain to me what I am doing wrong?
EDIT:
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*/);
}
Once a thread has completed running it is considered dead. Calling
isAliveon the same thread at this point will always return a result offalse. The JavaDoc for Thread does mention this: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:
For future reference, note that you can query a thread state via the
getStatemethod, which should help with analyzing errors, at the least.