6

I want to kill an specific thread but can't figure out a way of make it work. I include all info next, even if it does not seem important:

I use action bar sherlock and want to kill a thread on an action button event. So, i have:

    Thread myThread;
    myThread = new Thread(new Runnable(){
        public void run(){
                functionX();
        }
      });
    myThread.start();

This thread is a long running thread, and funcionX() creates some new threads as well. I want to kill the thread when:

   public boolean onOptionsItemSelected(MenuItem item){
    switch (item.getItemId()) {

    case android.R.id.home:
        myThread.interrupt();
        break;
    };

I've tried with ExecutorService, using submit(runnable) for a Future result and Future.cancel but does not seems to work. I should also mention that functionX() uses http get requests to get data from a JSON service.

Pete Carter
  • 2,691
  • 3
  • 23
  • 34
Moises B.
  • 637
  • 1
  • 8
  • 19

3 Answers3

5

there are multiple ways you can do this,couple of them can be like

  1. Instead of Thread use TimerTask and call timeTask.cancel() - for interrupting
  2. In the run() method of the thread, keep checking a boolean value to determine whether the thread should be terminated and then you can call interrupt or better throw an Exception
rock_win
  • 755
  • 1
  • 5
  • 14
  • +1. suggestion 2 is what I would use. If you are looping a thread fast, just include it at the top level, else have a few through the code. Before process hungry sections. – IAmGroot Nov 09 '12 at 16:09
  • Thanks. I will go with technique 2. – Moises B. Nov 12 '12 at 07:51
0

Option 2 from rock_win is the way to go, you can see why here with some code attached:

http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html

0

It's been years since this question has been asked but still, if someone needs, then you can use your thread object without any issues by using thread.interrupt();. That works without any issues and is good if you are new to Java or Threading in Java and want to stop a thread without changing a lot of things or switching to a different technology (like timertask).

Just in case you need to start the thread again, you need to re-initialize the Thread object to do so. So, In order to do this, i simply created a class that implemented a Runnable, so that i don't have to type much when i need to re-initialize the thread object. Then, whenever i needed to start the thread, i called

mythread = new Thread(new MyRunnable());  // initialize the thread
mythread.start();   // run the thread

Then when i need to stop it, then:

mythread.interrupt();  //stop the thread

And when i needed to start the thread again, then i had to again do:

mythread = new Thread(new MyRunnable());  //re-initialize the thread
mythread.start();   // start the new thread
Nalin Angrish
  • 317
  • 5
  • 17