在Asynctask中执行runnable

时间:2013-07-13 08:12:09

标签: android android-asynctask runnable

我有一个AsycnIntegerCounter课程,其AsyncTask延伸doInBackground()onPostExecute()。 从我的主线程,我能够创建一个可运行的对象并使用它来执行它 AsycnIntegerCounter的静态执行方法。 AsycnIntegerCounter.execute(Runnable)

任何人都可以帮助我理解当我们使用AsycnIntegerCounter(即)使用AsycnTask对象执行runnable时究竟发生了什么。

何时可以使用?什么是优势而不是使用Thread对象运行?

代码示例:

AsycnIntegerCounter integerCounter1 = new AsycnIntegerCounter(next,0);

AsycnIntegerCounter.execute(new Runnable() {

            @Override
            public void run() {

                int i = 100;
                while(i<=105){

                    i++;
                    try {
                        Thread.sleep(1000);

                    } catch (InterruptedException e) {

                        e.printStackTrace();
                    }
                }
            }
        });

4 个答案:

答案 0 :(得分:4)

之间存在一些根本区别
static void execute(Runnable)


AsyncTask execute(Params...)
  1. 后台任务在Runnable中定义,而不是实现doInBackground
  2. Runnable - 任务未使用AsyncTask的内部线程通信机制。因此,onPreExecuteonPostExecute都不会被调用。
  3. 后者适用于所有平台,而第一个是在API级别11中添加的。
  4. 使用execute(Runnable)的优点是任务可以在内部线程池的工作线程上执行,即不需要创建新线程。

答案 1 :(得分:1)

它与execute()相同,但它会在后台运行您的Runnable,而不是运行doInBackround功能。当你有相同的onPreExecute和onPostExecute但有几个runnables时它会很有用。

我认为优于Thread.executeExecutor的优势正好在之前和之后调用onPreExecuteonPostExecute

答案 2 :(得分:1)

据我所知,它类似AsyncTask类但AsynchTask只运行一次,但是这个类提供了两个东西 -

  1. 如果您希望任务多次运行,它会循环以便它受益 比如检查Web服务上的连续数据。
  2. 使用Thread.sleep修复了任务的运行时间,因此任务完成了 之前它将通过Thread.wait()确定此任务的时间。

答案 3 :(得分:1)

@Alex非常好。假设您有许多方法,M1()M2()等您希望执行的方法。假设在执行任何一个之前,您需要执行方法Before()并在需要执行方法After()之后。

即,方法的顺序如下:

Before();
M1();
After();

或者

Before();
M2();
After();

Before()放在onPreExecuteAfter() onPostExecute中,即可实现该序列。通过使M成为可运行的,您可以实现:

Before();
WhateverRunnableYouWant();
After();

在背景中使用Runnable,根据您的代码使用非UI线程。