线程如何停止

时间:2014-05-22 06:07:35

标签: android multithreading

public void onGenerate3() {
    Log.i("onGenerate", "WorkingStart");

//线程用于递归

    myActivity.myHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
                myActivity.myHandler.sendEmptyMessage(myActivity.GenerateBallonsForTargetScene);
                Log.i("onGenerate", "WorkingEnd");
    }, 1000);
}

//现在我想停止一个关于动作的动作我如何做到这一点

1 个答案:

答案 0 :(得分:0)

你不会停止一个线程,你想要做的是取消定时runnable的执行。

我认为this是一种方法。

Runnable myTask = new Runnable() {
  @Override
  public void run() {
    myActivity.myHandler.sendEmptyMessage(myActivity.GenerateBallonsForTargetScene);
    Log.i("onGenerate", "WorkingEnd");
}

// schedule the runnable
myActivity.myHandler.postDelayed(myTask, 1000);

// cancel the runnable
myActivity.myHandler.removeCallbacks(myTask);

当然,您也可以阻止执行代码:

// member variable
private boolean canceled;

Runnable myTask = new Runnable() {
  @Override
  public void run() {
    if (!canceled){
      myActivity.myHandler.sendEmptyMessage(myActivity.GenerateBallonsForTargetScene);
      Log.i("onGenerate", "WorkingEnd");
    }
}

// schedule the runnable
myActivity.myHandler.postDelayed(myTask, 1000);

// cancel
canceled = true;