使用线程的Android异步任务

4

我创建了一个异步任务,在它的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(),而我认为异步任务会在后台运行此线程,并在该布尔值为真时调用onPostExecute()。我无法理解为什么会发生这种情况?
3个回答

11

AsyncTask会自动为您创建一个新的线程,因此您在doInBackground()中执行的所有操作都在另一个线程上进行。
你正在做的是:

  1. AsyncTask创建一个新线程并运行doInBackground()
  2. 从AsyncTask-Thread创建了一个新线程(t)。
  3. doInBackground()已完成,因为它所做的只是创建线程t,然后跳转到onPostExecute()
  4. 线程t仍将在后台运行(但是,您没有调用tstart()方法,这意味着它未启动)。

相反,您希望doInBackground()方法看起来像这样:

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

谢谢你的建议,我现在明白问题所在了。 - user1254554
@user1254554 不错 :) 如果它帮到了你,应该接受一个答案(通过点击左侧得分下面的复选框),这将关闭问题并给回答者一个奖励。 - Jave
这里的 doInBackground() 中的 Thread 是否指向后台线程?我希望它不会阻塞用户界面。 - Alston
是的,在使用Thread.sleep()方法时会影响调用该方法的线程。由于它在doInBackground()中被调用,因此是后台线程在休眠。也就是说 - 它不会阻塞用户界面。 - Jave

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();
}

谢谢,我现在明白了问题。 - user1254554

1

onPostExecute 只能在 doInBackground 已经 return 后才能被调用。在你的代码中,唯一可能发生这种情况的方式是 sleep 抛出了一个 ExceptionInterruptedException?)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接