【android】HandlerThread的使用及源码剖析

来源:互联网 发布:linux terminal 编辑:程序博客网 时间:2024/06/06 12:32
有时候我们需要在应用程序中创建一些常驻的子线程不定期地执行一些计算型任务,这时候可以考虑使用HandlerThread,它具有创建带消息循环的子线程的作用。

一、HanderThread使用示例
先熟悉下HandlerThread的一般用法。我们创建一个如下所示的Activity:
[java] view plaincopy
  1. package com.example.handlethreaddemo;  
  2. import android.app.Activity;  
  3. import android.os.Bundle;  
  4. import android.os.Handler;  
  5. import android.os.HandlerThread;  
  6. import android.os.Looper;  
  7. import android.os.Message;  
  8. import android.util.Log;  
  9. public class MainActivity extends Activity  
  10. {  
  11.     private Looper mLooper;  
  12.     private MyHandler mHandler;  
  13.     private static final String TAG = "MainActivity";  
  14.     private static class MyHandler extends Handler  
  15.     {  
  16.         public MyHandler(Looper looper)  
  17.         {  
  18.             super(looper);  
  19.         }  
  20.         @Override  
  21.         public void handleMessage(Message msg)  
  22.         {  
  23.             switch (msg.what)  
  24.             {  
  25.             case 1:  
  26.                 Log.i(TAG, "当前线程是"+Thread.currentThread().getName()+",TEST 1");  
  27.                 break;  
  28.             case 2:  
  29.                 Log.i(TAG, "TEST 2");  
  30.                 break;  
  31.             }  
  32.         }  
  33.     }  
  34.       
  35.     @Override  
  36.     protected void onCreate(Bundle savedInstanceState)  
  37.     {  
  38.         super.onCreate(savedInstanceState);  
  39.         setContentView(R.layout.activity_main);  
  40.           
  41.         //创建HandlerThread对象  
  42.         HandlerThread myHandleThread = new HandlerThread("HandlerThread<子线程>");  
  43.         //启动HandlerThread---->内部将启动消息循环  
  44.         myHandleThread.start();  
  45.         //获取Looper  
  46.         mLooper = myHandleThread.getLooper();  
  47.         //构造Handler,传入子线程中的Looper  
  48.         mHandler = new MyHandler(mLooper);  
  49.         /* 
  50.          * 注:经过上述步骤,Handler将绑定子线程的Looper和MessageQueue. 
  51.          * 也就是说handleMessage最终由子线程调用 
  52.          * */  
  53.         mHandler.sendEmptyMessage(1);  
  54.           
  55.         Log.i(TAG,"当前线程是:"+Thread.currentThread().getName());  
  56.           
  57.     }  
  58.       
  59.       
  60. }  

使用HandlerThread内部提供的Looper对象构造Handler对象,然后在ui线程中向Handler发送消息。log日志如下:


可见发送消息的线程为UI线程,而处理消息的线程为子线程,也就是说,我们在子线程中创建了消息循环
一般情况下,我们总是在UI线程中创建Handler对象,并使用界面组件提供的默认Looper,这个Looper绑定在UI线程上。所以我们在线程中向Handler发送消息时,最终的处理是在主线程中进行的。但正如开篇所说,我们有时需要构建常驻的子线程以不定期执行计算型任务,这时在子线程中创建消息循环将非常有用。

二、HandlerThread源码剖析
HandlerThread源码十分精简。
HandlerThread继承自java.lang.Thread,并封装了Looper对象:
[java] view plaincopy
  1. int mPriority;//优先级  
  2.  int mTid = -1;//线程标志  
  3.  Looper mLooper;//消息循环  

可通过构造器注入线程优先级,默认优先级为Process.THREAD_PRIORITY_DEFAULT
[java] view plaincopy
  1. public HandlerThread(String name, int priority) {  
  2.        super(name);  
  3.        mPriority = priority;  
  4.    }  

核心逻辑为run方法(复写Thread类的run方法):
[java] view plaincopy
  1. public void run() {  
  2.        mTid = Process.myTid();  
  3.        Looper.prepare();//创建Looper对象  
  4.        synchronized (this) {  
  5.            mLooper = Looper.myLooper();//获取与本线程绑定的Looper  
  6.            notifyAll();  
  7.        }  
  8.        Process.setThreadPriority(mPriority);  
  9.        onLooperPrepared();//回调接口,默认为空实现。  
  10.        Looper.loop();//启动消息循环--->may be blocked  
  11.        mTid = -1;  
  12.    }  

外界可通过getLooper方法获取Looper对象:
[java] view plaincopy
  1. public Looper getLooper() {  
  2.        if (!isAlive()) {//线程死亡  
  3.            return null;  
  4.        }  
  5.          
  6.        // If the thread has been started, wait until the looper has been created.  
  7.        synchronized (this) {  
  8.            while (isAlive() && mLooper == null) {  
  9.                try {  
  10.                    wait();//异步等待Looper准备好  
  11.                } catch (InterruptedException e) {  
  12.                }  
  13.            }  
  14.        }  
  15.        return mLooper;  
  16.    }  

如果调用getLooper方法时,Looper未准备好,那么将会阻塞线程,直到准备好Looper对象。
外界可调用quit方法终止消息循环:
[java] view plaincopy
  1. public boolean quit() {  
  2.        Looper looper = getLooper();  
  3.        if (looper != null) {  
  4.            looper.quit();//内部调用looper类的quit  
  5.            return true;  
  6.        }  
  7.        return false;  
  8.    }  

附:
Looper类相信大家都不陌生,这里顺便简单提下(之前写过Handler和Looper):
Looper.prepare方法将会创建一个Looper对象(Looper类的构造器为私有,不可new),并将其放到ThreadLocal中,意为线程局部变量:
[java] view plaincopy
  1. public static void prepare() {  
  2.         prepare(true);  
  3.     }  
  4.     private static void prepare(boolean quitAllowed) {  
  5.         if (sThreadLocal.get() != null) {  
  6.             throw new RuntimeException("Only one Looper may be created per thread");  
  7.         }  
  8.         sThreadLocal.set(new Looper(quitAllowed));  
  9.     }  

然后通过Looper.myLooper方法返回与本线程绑定的Looper,正是刚创建的Looper:
[java] view plaincopy
  1. public static Looper myLooper() {  
  2.         return sThreadLocal.get();  
  3.     }  

Looper.loop方法将启动消息循环,不断从其内部封装的消息队列MessageQueue中取出消息,交由Handler执行。

[java] view plaincopy
  1. public static void loop() {  
  2.         final Looper me = myLooper();  
  3.         if (me == null) {  
  4.             throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");  
  5.         }  
  6.         final MessageQueue queue = me.mQueue;  
  7.         // Make sure the identity of this thread is that of the local process,  
  8.         // and keep track of what that identity token actually is.  
  9.         Binder.clearCallingIdentity();  
  10.         final long ident = Binder.clearCallingIdentity();  
  11.         for (;;) {  
  12.             Message msg = queue.next(); // might block  
  13.             if (msg == null) {  
  14.                 // No message indicates that the message queue is quitting.  
  15.                 return;  
  16.             }  
  17.             // This must be in a local variable, in case a UI event sets the logger  
  18.             Printer logging = me.mLogging;  
  19.             if (logging != null) {  
  20.                 logging.println(">>>>> Dispatching to " + msg.target + " " +  
  21.                         msg.callback + ": " + msg.what);  
  22.             }  
  23.             msg.target.dispatchMessage(msg);  
  24.             if (logging != null) {  
  25.                 logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);  
  26.             }  
  27.             // Make sure that during the course of dispatching the  
  28.             // identity of the thread wasn't corrupted.  
  29.             final long newIdent = Binder.clearCallingIdentity();  
  30.             if (ident != newIdent) {  
  31.                 Log.wtf(TAG, "Thread identity changed from 0x"  
  32.                         + Long.toHexString(ident) + " to 0x"  
  33.                         + Long.toHexString(newIdent) + " while dispatching to "  
  34.                         + msg.target.getClass().getName() + " "  
  35.                         + msg.callback + " what=" + msg.what);  
  36.             }  
  37.             msg.recycle();  
  38.         }  
  39.     }  
0 0
原创粉丝点击