I have one thread class which star in onCreate
of an activity.
class MyThread extends Thread
{
void run()
{
//My code which takes time.
}
}
//-------------------------- To run the thread
MyThread mThread = new MyThread();
mThread.start();
On some external events i need to stop/destroy currently running thread.
And Then i create a new copy of MyThread and call start
function on the new thread to run it.
But i am not able to destroy/stop the previous running thread.
Is there any API by which we can destroy running thread.
you cannot destroy...only the android will stop the thread when requires.. you cannot stop or destroy it.. instead try like this..
class MyThread extends Thread
{
void run()
{
while(bool){
//My code which takes time.
}
}
}
//-------------------------- To run the thread
MyThread mThread = new MyThread();
mThread.start();
now when u want to stop the thread... change bool value to false
bool=false;
now your code doesnt run... and you can start new thread...
The Thread.interrupt() method is the accepted way of stopping a running thread, but some implementation details are on you: if your thread is doing IO (or anything else that can throw InterruptedException), it's your responsibility to make sure that you close any resources you have open before you stop your thread.
This page indicates why some of the thread functionality present in earlier versions of Java was deprecated, and why Thread.destroy() was never actually implemented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With