我试过这种方式:
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)
王怡飞*_*王怡飞 13
mHandler.removeCallbacks(updateThread);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
81990 次 |
| 最近记录: |