I have a class (static) variable Thread t. In one method, t.start(); is executed to start thread, and this works. In another method, t.destroy(); is executed. But this does not work, the thread keeps on running. Can anyone help explain this? Thanks
Did you look at the Javadoc for Thread.destroy() ? Note especially the part I've emphasized in boldface.
Deprecated. This method was originally designed to destroy this thread without any cleanup. Any monitors it held would have remained locked. However, the method was never implemented. If if were to be implemented, it would be deadlock-prone in much the manner of suspend(). If the target thread held a lock protecting a critical system resource when it was destroyed, no thread could ever access this resource again. If another thread ever attempted to lock this resource, deadlock would result. Such deadlocks typically manifest themselves as "frozen" processes. For more information, see Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?.
Thanks, but I don't get it. I did check the API before, and it said Thread.stop() was deprecated, and Thread.destroy() wasn't. So it doesn't look like I can stop the thread, but I think I can break out of it. Thanks
author and iconoclast
Thread.destroy() has never been implemented in any JVM from Sun, except perhaps the Green Threads ones -- it's been a while so my memory fails me here.
In any case, use stop(), if you must, but use it only as an absolute last resort. Use interrupt() if you can, along with testing the interrupted property in your thread loop. [ November 13, 2005: Message edited by: Ernest Friedman-Hill ]
I use mainly two techniques to stop a thread. First, as Ernest alluded to, the interrupt() method. The interrupt() will cause the thread to throw an exception, at which point you can catch the exception and handle it in any number of ways. Specifically, you can use the catch block to kill your thread gracefully.
Second, use a global class variable which the thread will check on occasion to determine if it should still run.
Edited: Earlier I said I wasn't getting the interrupted exception, but I checked my little test program and I never interrupted the thread! Now I get it.
interrupt() and interrupted() seem to be designed for exactly this purpose, so I'd prefer them for their explicit communication of what I'm trying to do. I'm using them now in something else that has several sequential steps but no sleep or anything that throws InterruptedException. It checks for interrupted() after each step. [ November 14, 2005: Message edited by: Stan James ]
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi