我有一个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();
}
}
}
});
答案 0 :(得分:4)
之间存在一些根本区别
static void execute(Runnable)
和
AsyncTask execute(Params...)
doInBackground
Runnable
- 任务未使用AsyncTask
的内部线程通信机制。因此,onPreExecute
和onPostExecute
都不会被调用。使用execute(Runnable)
的优点是任务可以在内部线程池的工作线程上执行,即不需要创建新线程。
答案 1 :(得分:1)
它与execute()
相同,但它会在后台运行您的Runnable
,而不是运行doInBackround
功能。当你有相同的onPreExecute和onPostExecute但有几个runnables时它会很有用。
我认为优于Thread.execute
或Executor
的优势正好在之前和之后调用onPreExecute
和onPostExecute
。
答案 2 :(得分:1)
据我所知,它类似AsyncTask
类但AsynchTask
只运行一次,但是这个类提供了两个东西 -
Thread.wait()
确定此任务的时间。答案 3 :(得分:1)
@Alex非常好。假设您有许多方法,M1()
,M2()
等您希望执行的方法。假设在执行任何一个之前,您需要执行方法Before()
并在需要执行方法After()
之后。
即,方法的顺序如下:
Before();
M1();
After();
或者
Before();
M2();
After();
将Before()
放在onPreExecute
和After()
onPostExecute
中,即可实现该序列。通过使M
成为可运行的,您可以实现:
Before();
WhateverRunnableYouWant();
After();
在背景中使用Runnable
,根据您的代码使用非UI线程。