42

I tried this way:

private Runnable changeColor = new Runnable() {
   private boolean killMe=false;
   public void run() {
       //some work
       if(!killMe) color_changer.postDelayed(changeColor, 150);
   }
   public void kill(){
       killMe=true;
   }
};

but I can't access kill() method!

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
c0dehunter
  • 6,412
  • 16
  • 77
  • 139

5 Answers5

57

Instead implement your own thread.kill() mechanism, using existing API provided by the SDK. Manage your thread creation within a threadpool, and use Future.cancel() to kill the running thread:

ExecutorService executorService = Executors.newSingleThreadExecutor();
Runnable longRunningTask = new Runnable();

// submit task to threadpool:
Future longRunningTaskFuture = executorService.submit(longRunningTask);

... ...
// At some point in the future, if you want to kill the task:
longRunningTaskFuture.cancel(true);
... ...

Cancel method will behave differently based on your task running state, check the API for more details.

Bertram Gilfoyle
  • 9,899
  • 6
  • 42
  • 67
yorkw
  • 40,926
  • 10
  • 117
  • 130
  • If `longRunningTask` contains a list of tasks, how can I abort certain task's execution? There may be lots of thread running concurrently. – Alston Oct 23 '14 at 09:33
  • @DanielWilson I have a same problem. did you solve that? – Mahdi Jul 08 '15 at 09:31
  • .cancel method not found – Mayur Coceptioni Jul 30 '19 at 12:10
  • @Alston This is possible but you need to keep track of references. A list won‘t work, because of the return value of `void run()`. Collections do not store null. You could probably use a `Map` to accumulate references to each Runnable when you `submit(Runnable)` them. Alternatively, you could use a Callable+Collection, because the Callable can return something other than null. – Jonathan Komar Aug 16 '19 at 05:46
20
mHandler.removeCallbacks(updateThread);
David Wang
  • 934
  • 1
  • 12
  • 16
  • 9
    please, try to describe answer – Enamul Hassan Nov 02 '15 at 02:00
  • 2
    This is the easiest way for me. – bpiec Jan 10 '16 at 19:39
  • 2
    Actually, this seems to be the proper answer, as you don't have to create your own custom Runnable with all the yada-yada in it or use the ExecutorService. That's what the `removeCallbacks` method is there for. It's the closest to a JavaScript `clearTimeout`, same pattern. – Daniel F Jan 24 '17 at 03:10
  • 28
    This will only cancel pending runnables that have been posted to the thread queue. It will not stop the runnables which are already running. – GilCol Sep 27 '17 at 16:04
16
public abstract class StoppableRunnable implements Runnable {

    private volatile boolean mIsStopped = false;

    public abstract void stoppableRun();

    public void run() {
        setStopped(false);
        while(!mIsStopped) {
            stoppableRun();
            stop();
        }
    }

    public boolean isStopped() {
        return mIsStopped;
    }

    private void setStopped(boolean isStop) {    
        if (mIsStopped != isStop)
            mIsStopped = isStop;
    }

    public void stop() {
        setStopped(true);
    }
}

class ......

    private Handler mHandler = new Handler();

public void onStopThread() {
    mTask.stop();       
    mHandler.removeCallbacks(mTask);
}

public void onStartThread(long delayMillis) {
    mHandler.postDelayed(mTask, delayMillis);
}

private StoppableRunnable mTask = new StoppableRunnable() {
    public void stoppableRun() {        
                    .....
            onStartThread(1000);                
        }
    }
};
aLearner
  • 1,051
  • 14
  • 30
user1549150
  • 295
  • 3
  • 3
3

changeColor is declared as Runnable, which does not have a kill() method.

You need to create your own interface that extends Runnable and adds a (public) kill() method.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
-1

You can Use this way

Stop Runnable Thread //==============================================================================

 ThreadUtil.startTask(() -> {
                        // doTask
                    }, 1500);


//==============================================================================
 public class ThreadUtil {

        private static Handler handler;
        private static Runnable runnable;

        public static void startTask(IThreadTask iThreadTask, long delayTime) {
            stopTask();
            handler = new Handler();
            runnable = () -> {
                iThreadTask.doTask();
            };

            if (handler == null || runnable == null) {
                return;
            }

            handler.postDelayed(runnable, delayTime);

        }

        public static void stopTask() {
            try {
                handler.removeCallbacks(runnable);
                handler.removeCallbacksAndMessages(null);
                handler = null;
                runnable = null;

            }catch (Exception e){
                Log.e("ThreadUtil:","Error:"+e.toString());

            }

        }


        public interface IThreadTask {
            void doTask();
        }


    }
Shomu
  • 2,734
  • 24
  • 32