Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop or destroy a running Thread

Tags:

android

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.

like image 884
User7723337 Avatar asked Dec 10 '22 01:12

User7723337


2 Answers

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...

like image 98
5hssba Avatar answered Jan 05 '23 02:01

5hssba


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.

like image 40
Fishbreath Avatar answered Jan 05 '23 02:01

Fishbreath