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 isAlive
on the same thread at this point will always return a result of false
. The JavaDoc for Thread does mention this:
Tests if this thread is alive. A thread is alive if it has been started and has not yet 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();
}
For future reference, note that you can query a thread state via the getState
method, which should help with analyzing errors, at the least.
You must store the thread variable as a class member and create it only once. Most probably, you are storing it as a local variable and creating it everytime you push the button.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.