Handler and Android multithreading in detail

  • 2020-05-17 06:31:16
  • OfStack

Here's a piece of code you're all familiar with:


Handler handler = new Handler(); 
handler.post(myThread);

// Create using anonymous inner classes 1 A thread myThread
Runnable mythread = new Runnable() {
public void run() {
}
};

At first, many people thought that the run() method in myThread would run in a new thread, but it didn't.

handler in the above code does not call the start() method of thread myThread, but directly calls the run() method, which means that no new thread is actually created, just the run() method in the current thread.

This raises the question of if we put a time-consuming operation into the run() method, and then use an Handler object to put the thread post into the thread queue. Originally, we wanted to put these time-consuming operations in another thread so as not to affect the current process. The opposite is true: the code below post() must wait for the run() method to complete. If the current thread is the main thread, then the main program will be in a hard straight state.

So how do you implement real multithreading?

One of the easiest ways to do this is to use the multithreading method in JAVA directly, which is to create an Thread object and then call the start() method.

There is another method, the code is as follows:


//HandlerThread Set up the 1 Two new threads, it contains 1 a Looper
HandlerThread handlerThread = new HandlerThread("handler_Thread");
handlerThread.start();// Start the 1 A thread 
MyHandler myHandler = new MyHandler(handlerThread.getLooper());// Using a new thread Looper To establish 1 a Handler
// At this time MyHandler with 1 Two new threads are bound to 1 the 
Message msg = myHandler.obtainMessage();
msg.sendToTarget();// will message Pushed to provide message the Handler In the message queue 
// To establish 1 a Handler A subclass of 
class MyHandler extends Handler {
MyHandler(Looper looper) {
super(looper);
}
public void handleMessaage(Message msg) {
// The code that handles the message 
}
}

Today, I took a closer look at the Android document and found that although android supports the above two methods of setting up threads, it has one rule:

it violates the second rule of the single threaded model do not Android UI toolKit from the UI thread

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


Related articles: