HandlerThread 的用法 和Thread 的区别

来源:互联网 发布:模拟器软件闪退 编辑:程序博客网 时间:2024/05/16 05:53
 HandlerThread 继承了Thread 所以 具有Thread的特性,他的不同之处在哪里那?请看源码:
  @Override    public void run() {        mTid = Process.myTid();        Looper.prepare();        synchronized (this) {            mLooper = Looper.myLooper();            notifyAll();        }        Process.setThreadPriority(mPriority);        onLooperPrepared();        Looper.loop();        mTid = -1;    }

可以在run 方法中可以看到创建了这个线程的looper ,looper的构造函数中创建了唯一的消息队列MessageQueue, 每个线程只可能有唯一的looper 在Looper.loop()可以看到有个循环体,这个循环体就是不断从队列中取消息分发消息。

/**     * Run the message queue in this thread. Be sure to call     * {@link #quit()} to end the loop.     */    public static void loop() {        final Looper me = myLooper();        if (me == null) {            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");        }        final MessageQueue queue = me.mQueue;        // Make sure the identity of this thread is that of the local process,        // and keep track of what that identity token actually is.        Binder.clearCallingIdentity();        final long ident = Binder.clearCallingIdentity();        for (;;) {            Message msg = queue.next(); // might block            if (msg == null) {                // No message indicates that the message queue is quitting.                return;            }            // This must be in a local variable, in case a UI event sets the logger            Printer logging = me.mLogging;            if (logging != null) {                logging.println(">>>>> Dispatching to " + msg.target + " " +                        msg.callback + ": " + msg.what);            }            msg.target.dispatchMessage(msg);            if (logging != null) {                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);            }            // Make sure that during the course of dispatching the            // identity of the thread wasn't corrupted.            final long newIdent = Binder.clearCallingIdentity();            if (ident != newIdent) {                Log.wtf(TAG, "Thread identity changed from 0x"                        + Long.toHexString(ident) + " to 0x"                        + Long.toHexString(newIdent) + " while dispatching to "                        + msg.target.getClass().getName() + " "                        + msg.callback + " what=" + msg.what);            }            msg.recycleUnchecked();        }    }

HandlerThread常在什么情况下使用那?

重复使用线程来处理任务时,我们没有必要重复的创建thread 这样会印象程序的性能,这种情况尽量使用HandlerThread  

HandlerThread thread = new HandlerThread("MyHandlerThread"); thread.start(); mHandler = new myHandler(thread.getLooper()); mHandler.sendEmptyMsg(0);





0 0