if(!loadThread.isInterrupted()) {
So the answer depends on whether or not loadThread
is the current running thread or another thread running in your application. Since you are in the MainActivity
, the current running thread may be the main thread and the loadThread
is some background load thread that the current thread is checking the status of.
If loadThread
is the current thread then there really isn't any point in testing the interrupt flag. The Thread.sleep()
will throw immediately if the flag is set.
W/System.err: java.lang.InterruptedException
This is saying that the current running thread has been interrupted. You can see by the stack trace that the thread was in Thread.sleep(...)
when it threw. This may or may not have anything to do with loadThread
.
why does if(!loadThread.isInterrupted()) {
gets executed as true.
So if the loadThread
is the current running thread then it is very possible that it tests its interrupt status and then calls Thread.sleep()
. While it is sleeping is when the interrupt gets delivered. I assume this code is in some sort of test loop? The chances of the code getting interrupted outside of the sleep may be actually pretty small. This is classic race condition so the interrupt could be delivered before the isInterrupted()
or after during the sleep – the code has to be prepared for either possibility.
Lastly, in most situations it is recommended that you re-interrupt a thread when you catch InterruptedException
. The reason is that when InterruptedException
is thrown, the interrupt status of the thread is cleared. If you exit the routine, you want the calling code to be able to also test the interrupted flag – you don't want to clear it artificially. There are 3rd party libraries that catch and don't re-interrupt the thread which can cause major problems in threaded applications.
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
// immediately re-interrupt the thread so callers can test it too
Thread.currentThread().interrupt();
// deal with the interrupt which typically means exiting the the thread
return;
}