gpt4 book ai didi

java - 为什么 Android 的 AsyncTask 没有实现 Future?

转载 作者:搜寻专家 更新时间:2023-10-30 21:07:02 24 4
gpt4 key购买 nike

在 Java 中,我已经习惯了使用 Futures .现在我在看安卓,AsyncTask实现几乎所有相同的方法并涵盖相似的生命周期。但是,如果我想保持一致并在我的所有代码中使用 Future,我必须将 AsyncTask 包装在一个愚蠢的包装器中,因为它实际上并没有实现 Future。

他们只需要添加一个 isDone()方法,这看起来很简单,然后添加 implements Future<Result> . (稍后添加:请参阅下面的答案,了解它有多么微不足道)。

任何 Android 专家都知道一些很好的理由/模糊的错误可能导致为什么还没有这样做?

最佳答案

通过阅读 AsyncTask.java 的实际代码,它实际上使用一个Future 任务,然后还有更多。 Future 是一个异步执行的任务。 AsyncTask 被安排在单个(或多个)后台线程的队列上。

AsyncTask 实际上比 Future 任务更“高级”。它在 Future 的功能之上进行了花哨的调度和优化。看看API介绍层就知道了。 Future 从 API 1.0 开始就引入了。 AsyncTask 对象是在 API 3 中引入的。

AsyncTask 有一个 Future 任务,而不是一个 Future。

AsyncTask.java

/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*/
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);

Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
return postResult(doInBackground(mParams));
}
};

mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
try {
postResultIfNotInvoked(get());
} catch (InterruptedException e) {
android.util.Log.w(LOG_TAG, e);
} catch (ExecutionException e) {
throw new RuntimeException("An error occured while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}

关于java - 为什么 Android 的 AsyncTask 没有实现 Future?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11485482/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com