Android:如何停止Runnable?

Pri*_*alj 33 android runnable

我试过这种方式:

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;
   }
};
Run Code Online (Sandbox Code Playgroud)

但我无法访问kill()方法!

yor*_*rkw 46

而是thread.kill()使用SDK提供的现有API 实现您自己的机制.一中管理线程创建线程池,并使用Future.cancel()杀死正在运行的线程:

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);
... ...
Run Code Online (Sandbox Code Playgroud)

取消方法将根据您的任务运行状态而有所不同,请查看API以获取更多详细信息.


小智 15

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

上课......

    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);                
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

  • 你是否意识到这种实现会让你的Runnable烧掉CPU周期? (11认同)

王怡飞*_*王怡飞 13

mHandler.removeCallbacks(updateThread);
Run Code Online (Sandbox Code Playgroud)

  • 这将仅取消已发布到线程队列的挂起的可运行文件.它不会停止已经运行的runnables. (13认同)
  • 请尝试描述答案 (6认同)
  • 这对我来说是最简单的方法。 (2认同)
  • 实际上,这似乎是正确的答案,因为您不必创建包含所有 yada-yada 的自定义 Runnable 或使用 ExecutorService。这就是`removeCallbacks` 方法的用途。它最接近 JavaScript `clearTimeout`,同样的模式。 (2认同)