h开发者_Python百科elp me kill java thread So I have code:
new Thread(new Runnable() {
public void run() {
// process() method is time-consuming and has no while-loop in his body
// so I want to give user to stop it
new AnyObject().process();
}
}).start();
My question is how can I kill such thread?
You can call Thread.stop() however you should understand what it does as its deprecated for a reason (being that it can leave your system in an inconsistent state) If the work you are doing is self contained and well behaved, it won't be a problem.
However if it were well behaved you wouldn't need to stop it this way, thus the catch-22 with this "solution" ;)
Ultimately the only safe way to stop a thread is to have it exit its run loop. There are two main ways to do that, set a flag that the AnyObject.process method checks periodically or have the AnyObject.process method respond correctly to an interrupt and exit. However to use the latter method, you will need to keep a reference to the thread around so you can issue the interrupt method on it.
You should probably keep a reference to your AnyObject as well in case you need to reference it later.
If all that fails, System.exit() will usually do the trick.
You can call interrupt() on thread in order to stop it.
you can use thread.interrupt() to stop thread!
Your Thread will be terminated when the run() method will be terminated.
In your example, it will be when the new AnyObject().process();
will be terminated.
So, terminate the process() method will terminate your Thread.
精彩评论