机器人的AsyncTask与线程 [英] android asynctask with threading

查看:125
本文介绍了机器人的AsyncTask与线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个AsyncTask的,并在其doInBackground()方法,我开始这样一个主题:

I created an asynctask and in its doInBackground() method i started a thread like this:

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
  }
}

问题,我面对的是的第1次迭代后的视频下载() onPostExecute()被调用,相反,我认为的AsyncTask将运行在后台的主题,并当布尔值为true onPostexecute()是called.I我无法理解为什么会这样?

problem I am facing is after 1st iteration of Thread.sleep() , onPostExecute() is called , instead I thought that asynctask will run this thread on background and when that boolean is true onPostexecute() is called.I am not able to understand why this happens ?

推荐答案

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

AsyncTask automatically creates a new Thread for you, so everything you do in doInBackground() is on another thread.
What you are doing is this:

  1. AsyncTask的创建一个新的线程和运行 doInBackground()
  2. 在一个新的线程( T )从AsyncTask的线程创建的。
  3. doInBackground()完成,因为它的作用是创建线程t,从而跳到 onPostExecute()
  4. 在线程t仍然会在后台(但是,你不叫启动() T 运行的,这意味着它不启动)。
  1. AsyncTask creates a new Thread and runs doInBackground().
  2. a new Thread (t) is created from the AsyncTask-Thread.
  3. doInBackground() is completed, as all it does is create the Thread t and thus jumps to onPostExecute().
  4. Thread t would still be running in the background (however, you do not call start() on t, meaning that it is not started).

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

Instead you want your doInBackground() method to look something like this:

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

这篇关于机器人的AsyncTask与线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆