Detailed explanation of handler and Android multithreading

Here is a familiar Code:

The handler in the above code does not invoke the start () method of thread myThread, but directly calls the run () method, which means that actually does not create a new thread, just calling the run () method in the current thread.

This involves a problem. If we put a time-consuming operation into the run () method, and then use a handler object to post the thread to the thread queue. Originally, we wanted to put these time-consuming operations into another thread to avoid affecting the current process. But in fact, the opposite is true: the code below post () cannot continue until the run () method is executed. If the current thread is the main thread, the main program will be in a hard straight state.

So how to implement real multithreading?

One of the easiest ways is to directly use JAVA to implement multithreading, that is to create a Thread object and then call the start () method.

There is another method. The code is as follows:

It breaches the second rule of the single threaded model: do not access the Android UI toolkit from outside the UI thread

Android does not support modifying UI controls in threads other than UI threads. For example, if text is set for a textview, such an operation cannot be executed in a thread other than the UI thread, otherwise an exception will occur.

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
分享
二维码
< <上一篇
下一篇>>