android学习(2) 多线程的理解

多线程操做UI的运行原理:java

UI线程:首先启动app时,系统会自动启动一个UI线程,而后此线程会建立一个Looper(注:Looper构造函数会实例化一个MessageQueue的消息队列存在变量mQueue中),并经过调用loop方法来运行一个无限循环的for,此for里面经过MessageQueue.next()方法不间断的检索消息队列中的Message(若是消息队列为空,将阻塞等待),获取到Message后,则执行message.target(此字段存储的Handler类的实例)的dispatchMessage(Message msg)方法,而后执行recycle()方法回收Message对象(系统维护一个Message对象池,貌似为50个)。多线程

 

Handler:若是是子线程有结果须要反馈给UI线程,则Handler须要在UI线程中如实例化,反之则在子线程中实例化Handler。由于Handler默认实例化时使用的Looper为当前线程的Looperapp

Handler部分代码截取:async

public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }

        mLooper = Looper.myLooper();//此处就是设置获取当前线程的Looper存储到mLooper变量中
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
}

Handler类提供了多少构造器,能够直接指定使用那个线程的Looper。ide

public Handler(Looper looper)函数

更多的构造器,请参考源代码。oop

 

子线程:建立子线程(HandlerThread:默认建立本身的Looper,Thread:若是须要Looper则要本身手动建立),指定子线程须要执行的代码,在执行代码时若是有结果须要反馈给UI线程(如:显示值到UI上),则只要把此Handler(此Handler必须是UI线程的Handler,也就是必须使用的是UI线程的Looper实例)的Message压入到UI线程的MessageQueue中便可。获取此Handler对应的Message实例的方法:能够经过调用Handler的obtainMessage()方法。压入MessageQueue的方法:就是调用Handler中的sendMessage(sendEmptyMessageDelayed、sendEmptyMessageAtTime。。。。根据本身需求选择方法)或者调用Message的sendToTarget()方法,其实这个方法是message调用本身的target变量(存储Handler的实例)的sendMessage(Message msg)方法,而后把本身当成方法的参数传过去。this

 

补充:值得注意的是Handler的dispatchMessage方法spa

Handler部分代码以下:线程

final Callback mCallback;
public interface Callback {
        public boolean handleMessage(Message msg);
} 
     /* Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
    }
    
public void dispatchMessage(Message msg) {
        if (msg.callback != null) {//若是msg有callback下面的都不会执行了
            handleCallback(msg);
        } else {
            if (mCallback != null) {//若是Handler有本身的Callback,则根据返回结果来肯定是否执行handleMessage
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);//此为实现类必需要实现的方法
        }
    }

 

 

若有不正确或不严谨的地方欢迎指正、探讨。多谢!

相关文章
相关标签/搜索