Android interview questions (7) What is the principle of AsyncTask?

1. What is AsyncTask?

AsyncTask makes it possible to use the UI thread appropriately and simply. This class allows you to do something in the background and then tell the UI thread the progress and results, without having to manipulate handlers and threads.

2. What is the idea behind the design of AsyncTask?

AsyncTask is designed to be a helper class for Thread and Handler, not a general threading framework. AsyncTask should ideally be used for very short operations (a few seconds at most). If you want your threads to run for a long time, it is highly recommended that you use the APIs in the java.util.concurrent package. For example Executor, ThreadPoolExecutor and FutureTask

3. How does AsyncTask work?
The yellow background represents the UI thread, and the blue background represents the background thread. Note that the execution time of the background thread is very strict, which is a few seconds. In addition, it should be noted that all AsyncTask instances share a single-threaded background. Waiting and long-term operations in any AsyncTask instance may cause other AsyncTask instances to not be executed in time, and waiting may lead to deadlock. 4. What is AsyncTask suitable for? The following conditions must be met at the same time: a. The execution process is single, with only one input and one output. b. It takes a very short time but still needs to go to the background to do things and then update the UI. For example loading files, web pages or databases into the UI. c. The execution thread must be the UI thread d. No long-term maintenance of the state is required. 5. What is AsyncTask not suitable for? a. Long tasks. b. Tasks that can be called repeatedly.














c. Threads are required to perform multiple different tasks, and the tasks are related.
d. The execution thread is not the UI thread.
e. Some state still needs to be maintained after the task is executed.
f. The background service module needs to provide an independent API.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326121098&siteId=291194637