Why does not this thread stop in this situation?
I started a new thread to upload photos from the phone mobile to a computer webserver.
if (CMenu.retCommand == transferer)
{
thrdTrsfr = new Thread(this);
thrdTrsfr.start();
}
public void run() {
if (Thread.currentThread() == thrdTrsfr)
{
if (vButtonPhotos.size() > 0)
transfererPhotos("http://192.168.1.123/imfmobile/photoj2meupload/uploadphoto.php");
else
afficheAlert("Aucune photo à transférer !");
}
}
When the upload is finished then I stopped the thread. I tested the number of active threads before the upload. When I tested the number of running threads after stopping the upload thread, the number does not change. I must navigate back to the main screen then the number of active thread is the same at before the upload. I use this code to stop the upload thread :
if (thrdTrsfr != null && thrdTrsfr.isAlive())
{
thrdT开发者_运维知识库rsfr.interrupt();
thrdTrsfr = null;
}
So why must I go to the main screen in order to get the thread stopped?
Could it be that transfererPhotos()
is not finishing, perhaps due to waiting for an IO read of bytes that never arrives? If so, then the thread will stay alive forever, or until interrupted (as you are doing).
BTW, I can't see any value to the test for current thread:
if (Thread.currentThread() == thrdTrsfr) // Huh?
Calling Thread.interrupt()
does not kill a thread. It is more like asking the thread politely if it could stop now.
If the thread checks with
Thread.isInterrupted()
, it can see that it has been interrupted.If the thread is in a
sleep
orwait
call, the call will terminate with anInterruptedException
.Under some circumstances, a thread doing an IO operation might have the call terminated with an
InterruptedIOException
. (I've never been able to figure out whether this actually happens with modern JVMs, or whether this is just a legacy exception ...)
If none of the above happens, an interrupted thread will just keep running as if nothing has happened.
In your case:
- the
interrupt()
may not be noticed (as above), - your application (or some library) is catching and ignoring the interrupt, or
- there is a race condition and you are testing to see if the thread has died before it has had a chance to deal with the interrupt.
If your code checks thread count (by using activeCount()
) right after the following:
thrdTrsfr.interrupt();
thrdTrsfr = null;
In that case, the thread is probably not killed yet, when activeCount()
is called.
Try to add join()
call after the interrupt()
call. Then you can be sure that thread is really dead, when activeCount()
is called.
So, replace above code with the following:
thrdTrsfr.interrupt();
thrdTrsfr.join();
thrdTrsfr = null;
精彩评论