怎样停止AsyncTask和Thread

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

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

Java代码:


  1. package eoe.task;

  2. import android.app.Activity;
  3. import android.os.AsyncTask;
  4. import android.os.Bundle;
  5. import android.util.Log;
  6. import android.view.View;
  7. import android.view.View.OnClickListener;
  8. import android.widget.Button;

  9. public class AsyncTaskTest extends Activity {
  10. /** Called when the activity is first created. */


  11. @Override
  12. public void onCreate(Bundle savedInstanceState) {
  13. super.onCreate(savedInstanceState);
  14. setContentView(R.layout.main);
  15. //set the six buttons listener
  16. Button startButton=(Button) this.findViewById(R.id.StartTask);
  17. final TestAsyncTask task=new TestAsyncTask(0);
  18. startButton.setOnClickListener(new OnClickListener() {
  19. public void onClick(View v) {
  20. task.execute("str1","str2");
  21. }
  22. });
  23. Button endButton=(Button) this.findViewById(R.id.StopTask);
  24. endButton.setOnClickListener(new OnClickListener() {
  25. public void onClick(View v) {
  26. task.cancel(false);
  27. }
  28. });


  29. Button startSleepButton=(Button) this.findViewById(R.id.StartThread_sleep);
  30. final ThreadForTestSleep threadForTestSleep=new ThreadForTestSleep();
  31. startSleepButton.setOnClickListener(new OnClickListener() {
  32. public void onClick(View v) {
  33. threadForTestSleep.start();
  34. }
  35. });


  36. Button endSleepButton=(Button) this.findViewById(R.id.StopThread_sleep);
  37. endSleepButton.setOnClickListener(new OnClickListener() {
  38. public void onClick(View v) {
  39. threadForTestSleep.interrupt();
  40. }
  41. });


  42. Button startWaitButton=(Button) this.findViewById(R.id.StartThread_wait);
  43. final ThreadForTestWait threadForTestWait=new ThreadForTestWait();
  44. startWaitButton.setOnClickListener(new OnClickListener() {
  45. public void onClick(View v) {
  46. threadForTestWait.start();
  47. }
  48. });


  49. Button endWaitButton=(Button) this.findViewById(R.id.StopThread_wait);
  50. endWaitButton.setOnClickListener(new OnClickListener() {
  51. public void onClick(View v) {
  52. threadForTestWait.interrupt();
  53. }
  54. });
  55. }
  56. /**
  57. * AsyncTask
  58. * @author alex
  59. *
  60. */
  61. private class TestAsyncTask extends AsyncTask<String, Integer, Double>{
  62. double a;

  63. public TestAsyncTask(double a){
  64. this.a=a;
  65. }


  66. @Override
  67. protected Double doInBackground(String... params) {
  68. for(String param:params){
  69. Log.i("TestAsyncTask","param:"+param );
  70. }
  71. Log.i("TestAsyncTask", "doInBackground is start");
  72. for(int i=0;i<10000000;i++){
  73. a=i*i+i;
  74. Log.d("-----", "a:"+a);
  75. }
  76. Log.i("TestAsyncTask", "sleep 1 is end");
  77. try {
  78. Thread.sleep(30000);
  79. } catch (InterruptedException e) {
  80. // TODO Auto-generated catch block
  81. e.printStackTrace();
  82. }
  83. Log.i("TestAsyncTask", "sleep 2 is end and continue execute");
  84. return a;
  85. }


  86. protected void onPostExecute(Double result){
  87. Log.i("last a value is", ""+result);
  88. }
  89. }

  90. /**
  91. * test sleep
  92. * @author Administrator
  93. *
  94. */
  95. private class ThreadForTestSleep extends Thread{
  96. public void run(){
  97. Log.i("ThreadForTestWait", "sleep start");
  98. try {
  99. sleep(30000);
  100. } catch (InterruptedException e) {
  101. // TODO Auto-generated catch block
  102. e.printStackTrace();
  103. }
  104. double a;
  105. for(int i=0;i<10000000;i++){
  106. a=i*i+i;
  107. Log.d("-----", "a:"+a);
  108. }
  109. Log.i("ThreadForTestWait", "sleep end");
  110. }
  111. }


  112. /**
  113. * test wait
  114. * @author Administrator
  115. *
  116. */
  117. private class ThreadForTestWait extends Thread{
  118. public void run(){
  119. Log.i("ThreadForTestWait", "wait start");
  120. try {
  121. synchronized(this){
  122. wait();
  123. }
  124. } catch (InterruptedException e) {
  125. // TODO Auto-generated catch block
  126. e.printStackTrace();
  127. }
  128. Log.i("ThreadForTestWait", "wait end");
  129. }
  130. }
  131. }
复制代码

                 我们来看看这个例子怎么样,这里主要用到了 view.View.OnClickListener; 监听, android.widget.Button 按钮,我们定义一个 Button 是开始,一个 Button 定义为停止。这样我们就可以给按钮加上一个监听,在监听里定义当点击按钮时,就可以停止 AsyncTask Thread ,这个方法我个人感觉非常的好。这个主要是加了一个 sleep(30000); 这样的话,我们就有时间来判断一下是否应该怎么样做

你可能感兴趣的:(thread)