2012-03-30 86 views
4

的Android的AsyncTask我创建了一个的AsyncTask,并在其doInBackground()方法我开始这样一个线程:与线程

private class myAsyntask extends Asynctask{ 

    doInBackground(){ 
    Thread t = new Thread(new Runnable(){ 
    public void run() 
    { 
     while(someBoolean!=true){ 
     Thread.currentThread.sleep(100); 
     } 
    } 
    }); 
    } 
    onPostExecute(){ 
    //do something related to that variable 
    } 
} 

问题,我面对的是Thread.sleep()第一次迭代后,onPostExecute()被调用,而不是我想那asynctask会在后台运行这个线程,当这个boolean值为true onPostexecute()被调用时,我无法理解为什么会发生这种情况?

回答

11

的AsyncTask自动为您创建一个新的线程,让你在doInBackground()所做的一切都是在另一个线程。
你在做什么,这是:

  1. 的AsyncTask创建一个新线程,并运行doInBackground()
  2. 从AsyncTask-Thread创建一个新的主题(t)。
  3. doInBackground()已完成,因为它所做的只是创建线程t并跳转到onPostExecute()
  4. 线程t仍然会在后台运行(但是,您不要在t上调用start(),这意味着它不会启动)。

相反,你希望你的doInBackground()方法看起来是这样的:

doInBackground(){ 
    while(someBoolean!=true){ 
     //Perform some repeating action. 
     Thread.sleep(100); 
    } 
} 
+0

感谢我的理解是什么问题,现在建议等待它的完成。 – user1254554 2012-03-30 08:43:41

+0

@ user1254554好:)如果它对你有帮助,你应该接受一个答案(点击左边分数下的复选标记)。这既关闭了问题,也回答了回答的人。 – Jave 2012-03-30 08:47:11

+0

'doInBackground()'中的线程是否指向后台线程?我希望它不会阻止用户界面。 – Stallman 2014-10-08 10:36:28

1

onPostExecute只能在doInBackgroundreturn -ed时才能调用。在代码中,唯一可能的方式会发生这种情况是sleep抛出ExceptionInterruptedException ??)

3

首先,在你的代码,你甚至不启动线程t,让所有发生在doInBackground是创造新线程,然后移动到onPostExecute()

其次,你甚至不需要单独的线程,因为doInBackground()为您处理此,所以你可以使用类似

doInBackground(){ 
    while(someBoolean!=true){ 
     Thread.currentThread.sleep(100); 
    } 
} 

,如果你愿意的话,但是,与单独的线程坚持,你可以启动线程,并通过使用.join();

doInBackground(){ 
    Thread t = new Thread(new Runnable(){ 
     public void run() { 
      while(someBoolean!=true){ 
       Thread.currentThread.sleep(100); 
      } 
     } 
    }); 
    t.start(); 
    t.join(); 
} 
+0

谢谢,我现在明白了这个问题 – user1254554 2012-03-30 08:44:23