Detailed explanation of Android multithreading

handler. In fact, post (R) does not start a new thread. It just executes the run () method in runnable, but does not execute the start () method, so runnable still runs the UI thread.

1. If you like this, you can operate the UI, but run still goes in the main thread. See that the printed log thread name is main, indicating that it is the main thread.

This is why you can manipulate the UI directly in the run method, because it is still a UI thread in essence

2. The looper obtained through the handlerthread can start a new thread, but it is impossible to operate the UI in the run method here, but this obviously has a disadvantage. If you execute the post (R) method multiple times, you still use the handlerthread thread thread. If you execute five times, n times, actually once, and they are serial. If you download 5 pictures, you will see that the picture is the first one before you go to the second one.

Practice has proved that only the handler with the loop of the main thread can operate the UI, and the UI in the main thread can operate UI in the handler's handlermessage () method or UI in the handler's post (R) run method

How to do this? Hehe, you can build a handler without parameters. Use this handler to send and process messages, and use the above handler to start a new thread.

Print log:

3. In fact, the second method is cumbersome and inefficient. It uses two handlers, one for initiating threads and the other for processing messages. The handler that initiates the thread must have a looper, so you need to instantiate a handerthread; The handler that handles messages does not need a looper, because it has the looper of the main thread by default, so it can handle the UI in this handler.

In fact, you only need to instantiate a handler, build a parameterless handler in the main thread, and then send and process messages. The task of creating a thread does not need a handler, but directly uses new thread (R) start(); Then the logical transaction is processed in the run () method of R.

If you download five pictures in this mode, you may not see the pictures displayed one by one. The second picture may come out first or three pictures may come out at the same time. The five threads are very random.

Print log:

4.AsyncTask

In fact, the multi task model based on asynchronous task architecture is not very robust. You have to create multiple asynctask instances. An asynctask is executed only once and cannot be executed repeatedly. The threads of fast food class are used up at one time.

The two most important methods to implement the asynctask subclass are doinbackground (params); One is onpost execute (result). Handle time-consuming transactions in the doinbackground () method and return the results. The returned value will be used as a parameter in the onpostexecute method, and then the results can be displayed on the UI in onpostexecute ().

Steps:

① Instantiate asynctask:

Instantiate asynctask and then use task exec(pamas); Pass in parameters. The parameter list is dynamic. It can be one or multiple, with variable length.

Asynctask < params, values, reslut >, the first parameter will be passed into the method doinbackground (params), the second parameter is the value of data update, and the third parameter is the result returned from transaction processing.

② Onpreexecute method:

This method has no parameters and no return value. You can make some reminders in this method. For example, show a dialog or play a toast to tell the user to start downloading.

③ Doinbackground (params) method:

Enter the internal structure of asynctask. First, the reslut doinbackground (params) method will be executed. This method will process time-consuming transactions. The parameters of exec () will be passed into this method as parameters, and the return value will be used as the parameters of onpostexecute (). If you want to update the progress, you need to execute the publicprogress () method.

④ Onprogressupdate (values) method:

The parameters of this method must execute the publicprogress () method in the doinbackground () method. This method will pass the parameters into the onprogressupdate () method, and then make some UI update display in this method. For example, the value of the progress bar can be changed dynamically through this values value.

⑤ Onpostexecute (result) method:

Here is the method to go after the transaction is completed. The execution result of the doinbackground method will be transmitted here if the method returns data. UI can be processed in this method, and the processed data can be displayed on the UI. For example, pictures, words, all the results you want.

Log printed here

5. Executorservie thread pool

There are three kinds of static methods to create through executors:

1. Single thread: executors newSingleThreadExecutor();

2. Fixed number of threads: executors newFixedThreadPool();

3. Dynamic thread: executors newCachedThreadPool();

Here, we use five fixed threads to apply. The method is to create an executorservice object, and then execute submit (R) to initiate a runnable object. The advantage of managing with thread pool is that it can ensure the stable operation of the system. It is applicable to the situation with a large number of threads and high workload. If 1000 pictures are to be displayed, if 1000 threads are created to load, the system will die. This problem can be avoided by using thread pool. Five threads can be executed in turn and in groups of five. The executed threads are not recycled directly, but wait for the next execution. In this way, the overhead of the system can be reduced a lot.

Log:

In fact, it may not be clear that the first is not multithreading.

1. Loadimagesbyhandler() is through handler Post () method to build two handlers to communicate.

2. Loadimagesbythread(), which is a thread directly initiated by new thread(), processes messages in the handler of the main thread

3. Loadimagebyasynctask(), which is an asynchronous task, is implemented in its internal structure and can operate UI

4. Loadimagesbyexectors () uses thread pool to make threads controllable and ensure stable operation.

In fact, the latter three are commonly used. The second usage is flexible and simple, but it is not suitable for a large number of tasks; The third is generally applicable to a single task, a one-time task; The fourth one is generally used for large number and high-density execution scenarios, such as batch loading pictures, batch downloading files, etc.

Take a look at the picture:

Full source code:

The above is the data sorting of Android multithreading. We will continue to supplement relevant knowledge in the future. Thank you for your support for this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>