Android/java 多线程(二)-Thread的好兄弟Handler

上一篇带大家了解了Thread的使用以及基本的运行原理,这一篇就带大家了解下Thread的好兄弟Handler

Android/java 多线程(一)-Thread的使用以及源码分析

简介

Handler机制在安卓中应用非常广泛,像我们常见的用于在子线程中更新UI:

public class MainActivity extends AppCompatActivity {

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            //更新UI
        }
    };
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyThread thread = new MyThread();
        thread.start();
    }

    class MyThread extends Thread {

        @Override
        public void run() {
             //处理子线程逻辑
            //....
            //发送消息更新UI
            Message message = mHandler.obtainMessage(1);
            mHandler.sendMessage(message);
        }
    }
}

由此引出一些问题,为什么sendMessage之后handleMessage方法会被执行?.为什么handleMessage是在主线程中?.它们的消息是如何传递的?.这些会在下面讲解

且看还有一种使用情况,在子线程中使用Handler:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyThread thread = new MyThread();
        thread.start();
    }

    class MyThread extends Thread {

        @Override
        public void run() {
            Looper.prepare();
            @SuppressLint("HandlerLeak")
            Handler mHandler = new Handler(){
                @Override
                public void handleMessage(Message msg) {
                     //处理逻辑
                    l(Thread.currentThread().getName());
                }
            };
            Message message = mHandler.obtainMessage(1);
            mHandler.sendMessage(message);
            Looper.loop();
        }
    }

    public void l(String s) {
        Log.i("HJ", s);
    }
}

打印结果如下:

2018-12-20 10:48:21.682 1808-1824/? I/HJ: Thread-2

如果我们不使用Looper.prepare()Looper.loop()方法,直接运行,那么会抛出以下异常:

2018-12-20 11:00:49.654 2029-2045/com.zj.example.customview.funnel E/AndroidRuntime: FATAL EXCEPTION: Thread-2
    Process: com.zj.example.customview.funnel, PID: 2029
    java.lang.RuntimeException: Only one Looper may be created per thread
        at android.os.Looper.prepare(Looper.java:95)
        at android.os.Looper.prepare(Looper.java:90)
        at com.zj.example.customview.funnel.MainActivity$MyThread.run(MainActivity.java:48)

这是为什么呢?,为什么子线程不能直接创建Handler呢?使用了Looper.prepare()Looper.loop()为什么又可以了呢?,这两个方法又是干什么用的呢?请看以下源码分析。

原理分析

Handler机制的核心类主要有三个,Handler ,Message,Looper,而与Looper相关联的类还有ThreadLocalMessageQueue,下面来一一介绍下它们的作用:

Message

消息的载体,内部主要存放一些消息类型,参数主要有:
(1)public int what:变量,用于定义此Message属于何种操作
(2)public Object obj:变量,用于定义此Message传递的信息数据,通过它传递信息
(3)public int arg1:变量,传递一些整型数据时使用
(4)public int arg2:变量,传递一些整型数据时使用
(5)public Handler getTarget():普通方法,取得操作此消息的Handler对象。
在该类的使用上,尽量使用obtain()方法来获取,而非构造方法,这样可以节省内存。而在数据传递方面,如果是int类型的,建议使用arg1arg2,其次再考虑使用Bundle

Looper

消息通道,消息机制的主要逻辑实现类,内部有使用ThreadLocal用来保存当前线程的Looper,使用MessageQueue用来维护Message池,而我们使用Looper.prepare()方法其实也就是将此线程的Looper对象加入到ThreadLocal中去:

    public static void prepare() {
        prepare(true);
    }

    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
         //一个线程只能创建一个Looper
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }

看源码就知道,当前线程中有且只有一个Looper,当我们再次创建,就会抛出异常,所以上面抛异常的原因就是在这里。

而我们的loop()方法就是消息机制的核心,原理是实现了一个无限循环,用于从MessageQueue中取出消息分发到各个Handler中去,以下是精简源码:

public static void loop() {
        //从ThreadLocal中取出Looper
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
       //从Looper中获取到MessageQueue 
        final MessageQueue queue = me.mQueue;

        ........
        //创建循环
        for (;;) {
            //从MessageQueue中一个一个的取出Message
            Message msg = queue.next(); // might block
            if (msg == null) {
               //没消息取了就退出
                return;
            }
           ...........
            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            try {
               //dispatchMessage方法的调用在这
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            .........
           //回收消息,同时将Message置为空消息对象,存储在消息池中,用于obtain()方法再次获取
            msg.recycleUnchecked();
        }
    }

综合要点就是使用loop()来开启消息分发,并且使用prepare来创建Looper。并且一个线程只能有一个Looper

可以看到,dispatchMessage就是在这里回调的,那这个target是什么东西呢,其实就是我们的Handler对象。那这个Handler对象是在哪里赋值的呢,请看Handler源码

Handler

首先看我们的构造方法最终会调用到这里:

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());
            }
        }
         //这里就将Looper创建好了,主要这里是在主线程中
        mLooper = Looper.myLooper();
        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;
}

这里主要起到从ThreadLocal中获取Looper对象的作用。看Looper.myLooper()方法:

    /**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

随后我们会调用sendMessage()类型的方法来发送消息,最终都会调用这个方法:

    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this; //这里将Handler赋值了
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

注意看这里msg.target = this,这里实现了将当前Handler赋值到了Message中。随后调用了enqueueMessage方法就将此Message投入到了消息池MessageQueue中.到这里,一系列的初始化与调用都完成了。

所以,经过以上分析,我们之前的问题就迎刃而解了,但是还是有一个问题,我们在第一个实例中并没有使用Looperprepareloop方法,那我们的消息机制为什么会生效呢,其实在我们的app创建的时候系统已经默认为我们开启了,并且是在主程序的最后调用的,并没有在onCreate()方法中,而其他的生命周期方法,是通过AMS进行回调。这就保证了我们的循环不会造成主线程卡顿,具体的源码调用是在ActivityThread类中的main函数中:

public static void main(String[] args) {
    SamplingProfilerIntegration.start();

    // CloseGuard defaults to true and can be quite spammy.  We
    // disable it here, but selectively enable it later (via
    // StrictMode) on debug builds, but using DropBox, not logs.
    CloseGuard.setEnabled(false);

    Environment.initForCurrentUser();

    // Set the reporter for event logging in libcore
    EventLogger.setReporter(new EventLoggingReporter());

    Security.addProvider(new AndroidKeyStoreProvider());

    // Make sure TrustedCertificateStore looks in the right place for CA certificates
    final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
    TrustedCertificateStore.setDefaultUserDirectory(configDir);

    Process.setArgV0("<pre-initialized>");

    Looper.prepareMainLooper();  // //为当前线程(主线程)创建一个Looper对象

    ActivityThread thread = new ActivityThread();
    thread.attach(false);

    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();  //为当前线程设置Handler
    }

    AsyncTask.init();

    if (false) {
        Looper.myLooper().setMessageLogging(new
                LogPrinter(Log.DEBUG, "ActivityThread"));
    }

    Looper.loop();  // 执行从消息队列中获取Message,并调用Handler进行处理的无限循环;所有和主线程相关的消息处理都在该方法中执行

    throw new RuntimeException("Main thread loop unexpectedly exited");
}

分析到这,Handler流程其实也差不多了,最后做下总结:

1.在主线程中初始化了一个Handler,此时Looper.loop()已经开启,通过Handler构造方法创建了一个在主线程中的Looper,并保存到了ThreadLocal中,此时主线程不允许再创建第二个Looper.

2.在子线程中使用sendMessage方法,此时会调用enqueueMessage()方法并创建一个Message(或从池中取出空Message对象),然后我们将需要发送的消息保存在Message中,并将此Handler保存到Message的target对象中,然后压入到MessageQueue消息池中

3.Looper中会循环从MessageQueue中取出Message对象,并回调到target对象上的Handler的dispatchMessage()方法中去,由于Looper.loop()方法是在主线程中调用,所以dispatchMessage()方法也是运行在主线程中。Looper.loop()方法运行所在的线程决定dispatchMessage()方法回调的线程,并且需要与Looper.prepare()方法配套使用

    原文作者:我是黄教主啊
    原文地址: https://www.jianshu.com/p/35ace3aa0022
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞