怎样停止AsyncTask和Thread

在java的线程中,没有办法停止一个正在运行中的线程。在Android的AsyncTask中也是一样的。如果必须要停止一个线程,可以采用这个线程中设置一个标志位,然后在线程run方法或AsyncTask的doInBackground方法中的关键步骤判断这个标志位以决定是否继续执行。然后在需要终止此线程的地方改变这个标志位以达到停止线程的目的。

 

    从外部调用AsyncTask的cancel方法并不能停止一个已经启动的AsyncTask。这个cancel方法的作用与线程的interrupt方法相似,调用了一个线程的interrupt方法之后线程仍然运行,但是如果该线程的run方法里面调用过sleep的或者wait方法后,处于sleep或wait状态,则sleep和wait立即结束并且抛出InterruptedException异常。AsyncTask的cancel方法也一样,如果在这个Task的doInBackground方法中调用了sleep或wait方法,当在UI线程中调用了这个Task实例的cancel方法之后,sleep或wait立即结束并且抛出InterruptedException异常,但是如果捕获该异常的代码后面还有其他代码,则这些代码还会继续执行。测试代码如下:

package com.task;


import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


public class AsyncTaskTest extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //set the six buttons listener
        Button startButton=(Button) this.findViewById(R.id.StartTask);
        final TestAsyncTask task=new TestAsyncTask(0);
        startButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
task.execute("str1","str2");
}
});
        Button endButton=(Button) this.findViewById(R.id.StopTask);
        endButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
task.cancel(false);
}
});
        Button startSleepButton=(Button) this.findViewById(R.id.StartThread_sleep);
        final ThreadForTestSleep threadForTestSleep=new ThreadForTestSleep();
        startSleepButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
threadForTestSleep.start();
}
});
        Button endSleepButton=(Button) this.findViewById(R.id.StopThread_sleep);
        endSleepButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
threadForTestSleep.interrupt();
}
});
        Button startWaitButton=(Button) this.findViewById(R.id.StartThread_wait);
        final ThreadForTestWait threadForTestWait=new ThreadForTestWait();
        startWaitButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
threadForTestWait.start();
}
});
        Button endWaitButton=(Button) this.findViewById(R.id.StopThread_wait);
        endWaitButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
threadForTestWait.interrupt();
}
});
    }
    /**
     * AsyncTask
     * @author alex
     *
     */
    private class TestAsyncTask extends AsyncTask<String, Integer, Double>{
     double a;

public TestAsyncTask(double a){
this.a=a;
}
@Override
protected Double doInBackground(String... params) {
for(String param:params){
Log.i("TestAsyncTask","param:"+param );
}
Log.i("TestAsyncTask", "doInBackground is start");
for(int i=0;i<10000000;i++){
a=i*i+i;
Log.d("-----", "a:"+a);
}
Log.i("TestAsyncTask", "sleep 1 is end");
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("TestAsyncTask", "sleep 2 is end and continue execute");
return a;
}
protected  void onPostExecute(Double result){
Log.i("last a value is", ""+result);
}
    }
    
    /**
     * test sleep
     * @author Administrator
     *
     */
    private class ThreadForTestSleep extends Thread{
     public void run(){
     Log.i("ThreadForTestWait", "sleep start");
     try {
sleep(30000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
double a;
for(int i=0;i<10000000;i++){
a=i*i+i;
Log.d("-----", "a:"+a);
}
Log.i("ThreadForTestWait", "sleep end");
     }
    }
    /**
     * test wait
     * @author Administrator
     *
     */
    private class ThreadForTestWait extends Thread{
     public void run(){
     Log.i("ThreadForTestWait", "wait start");
     try {
     synchronized(this){
     wait();
     }
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("ThreadForTestWait", "wait end");
     }
    }
}


转自http://alex-yang-xiansoftware-com.iteye.com/blog/839662

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值