Concurrent processing of Android threads and android thread concurrency
The previous article introduced the simple logoff knowledge. In this article, we will introduce the concurrent processing of multiple threads. We know that the messages sent by Handler through sendMessage () are first sent to logoff, store the logoff message stack and send it from the new Handler object. The Handler object processes the message through the handMessage () method. Here it is easy to see a null pointer exception. Let's take a look at this Code:
Public class MainActivity extends Activity {class Mythread extends Thread {private Handler handler; private Looper loler; @ Override public void run () {looper. prepare (); // create a logoff object logoff = logoff. mylofter (); handler = new Handler () {@ Override public void handleMessage (Message msg) {System. out. println ("sub-Thread:" + Thread. currentThread () ;}}; Looper. loop (); // loop processing method through this method}; private Mythread thread; private Handler secondHandler; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); thread = new Mythread (); thread. start (); try {Thread. sleep (3000);} catch (InterruptedException e) {e. printStackTrace ();} thread. handler. sendEmptyMessage (1); // process secondHandler = new Handler (thread. logoff) {@ Override public void handleMessage (Message msg) {System. out. println (msg) ;}}; secondHandler. sendEmptyMessage (1 );}}
This will cause a null pointer exception, because when we create the SecondHandler, if the thread. logoff object has not been created, this exception will occur. So how can we prevent this exception? Google has taken this into consideration when designing Android. Here we will use HandlerThread to handle this multi-thread concurrency problem.
/*** NULL pointer problem occurs when HandlerThread is used to process multi-thread concurrent processing */public class SecondActivity extends Activity {private HandlerThread handlerThread; private Handler handler; private TextView text; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); // create a TextView text = new TextView (this); text. setText ("Helloword"); setContentView (text); // create a Handler thread object handlerThread = new HandlerThread ("handler thread "); // name handlerThread for the current thread. start (); // start thread handler = new Handler (handlerThread. getLooper () {@ Override public void handleMessage (Message msg) {System. out. println ("current:" + Thread. currentThread () ;}}; handler. sendEmptyMessage (1 );}}