Please explain to me why do the following code throw IllegalThreadStateException?
try
{
if(thread1 != null)
{
if(thread1.isAlive());
{
thread1.interrupt(); //it is ok
thread1.join();
}
}
if(thread2 != null)
{
if(thread2.isAlive());
{
thread2.interrupt(); //throw IllegalThreadStateException
thread2.join();
}
}
}
catch(IllegalThreadStateException e)
{
System.exit(0);
}
It threw IllegalThreadStateException when run statement thread2.interrupt(). But thread1.interrupt() is ok.
Please explain to me.
Many thanks!
The line:
is not doing what you think it’s doing 🙂 The code segment:
will check if the thread is alive and, if so, execute that empty statement before the semicolon. It will then execute the
interrupt/joinsequence inside the braces no matter what the state of the thread was. That’s because:is a perfectly valid Java construct, even without an
iforwhilepreceding it. Change:to:
(and do the same for the
thread1check as well).And you should also call
getMessage()on the exception to find out the specific details, if any.It may contain extra information for easier root cause analysis.