HanderThread的quit和interrupt

使用Java的时候, 我们一般都是使用interrupt结束线程. 那么使用Android 的HandlerThread怎么结束一个线程呢?

 

我们知道 HanderThread其实就是一个里吗有个Looper在死循环的普通Thread

 @Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }

Looper.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();
        }
    }

 

原来是

 Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

 

那什么时候msg = null呢? 这里的queue是 MessageQueue.java

Message next() {
        // Return here if the message loop has already quit and been disposed.
        // This can happen if the application tries to restart a looper after quit
        // which is not supported.
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }

            nativePollOnce(ptr, nextPollTimeoutMillis);

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (false) Log.v("MessageQueue", "Returning message: " + msg);
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }

                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose();
                    return null;
                }

                // If first time idle, then get the number of idlers to run.
                // Idle handles only run if the queue is empty or if the first message
                // in the queue (possibly a barrier) is due to be handled in the future.
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }

                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }

            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            for (int i = 0; i < pendingIdleHandlerCount; i++) {
                final IdleHandler idler = mPendingIdleHandlers[i];
                mPendingIdleHandlers[i] = null; // release the reference to the handler

                boolean keep = false;
                try {
                    keep = idler.queueIdle();
                } catch (Throwable t) {
                    Log.wtf("MessageQueue", "IdleHandler threw exception", t);
                }

                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;

            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            nextPollTimeoutMillis = 0;
        }
    }

 

有两个地方, 第一个是初始化C++层对象的一个指针. 第二个就是mQuiting =true

调用quit的时候会导致mQuiting = true, 那Looper就会退出了.HanderThread也就退出了. 此时也把C++层真正的NativeMessageQueue对象销毁了

而interrupt 其实是调用了Thread.java的interrupt方法, 也就是 把暴力线程终止了.

 

PS: 为了提高效率, MessageQueue.java不负责真正的队列操作,  真正的对了操作使用了linux pipe实现,  所以有了那个mPtr, 它指向Linux层的NativeMessageQueue. 更多请参考 http://blog.csdn.net/u010018855/article/details/50221079

 

 

转载于:https://my.oschina.net/sfshine/blog/1548749

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: driver.quit和close都是Selenium WebDriver中的方法,用于关闭浏览器窗口。 区别在于: 1. driver.quit()会关闭所有打开的浏览器窗口,并且结束WebDriver进程。而close()只会关闭当前窗口,如果当前窗口是最后一个窗口,则也会结束WebDriver进程。 2. driver.quit()会触发所有WebDriver实例的quit事件,可以用来清理资源和做一些收尾工作。而close()只是关闭当前窗口,不会触发任何事件。 因此,如果你只需要关闭当前窗口,可以使用close()方法。如果你需要关闭所有窗口并结束WebDriver进程,可以使用quit()方法。 ### 回答2: 在Selenium测试中,常用的关闭浏览器的方法有driver.quit()和driver.close()。这两个方法都可以将浏览器关闭,但它们的实现方式和影响略有不同。 driver.quit()方法: driver.quit()方法会关闭所有相关的浏览器窗口,并杀死与其相关的进程和驱动程序。这意味着,当使用driver.quit()方法时,Selenium将会完全终止与该浏览器相关的所有进程,包括浏览器窗口、浏览器驱动程序和驱动程序的后台服务。因此,当使用这个方法时,不需要再单独清除或关闭任何窗口或进程。 driver.close()方法: 相反地,driver.close()方法只会关闭当前的浏览器窗口,而不会关闭与其相关的进程和驱动程序。这意味着,当使用driver.close()方法时,只会关闭当前的浏览器窗口,而其他相关的窗口、进程和驱动程序将继续运行。 因此,我们可以在需要关闭浏览器的场合下使用两个方法。如果需要退出Selenium测试,并且不需要再使用此浏览器进行任何操作或测试,则应使用driver.quit()。如果只需要关闭当前窗口,然后继续使用其他窗口和进程,则应使用driver.close()。 总结: 1. driver.quit()会关闭所有相关的浏览器窗口,并杀死与其相关的进程和驱动程序; 2. driver.close()只会关闭当前的浏览器窗口,而不会关闭与其相关的进程和驱动程序; 3. 如果需要退出Selenium测试或需要完全清理所有窗口和进程,请使用driver.quit(); 4. 如果只需要关闭当前窗口并保留其他浏览器窗口和进程,请使用driver.close()。 ### 回答3: 在自动化测试中,关闭浏览器窗口是一个常见的需求。Selenium 提供了两种方法来关闭浏览器窗口,即 driver.quit() 和 driver.close() 方法。两者的主要区别如下: 1. 区别 - driver.quit():关闭所有浏览器窗口,并停止驱动程序。 - driver.close():只关闭当前浏览器窗口,不停止驱动程序。 2. 应用场景 - driver.quit():当测试用例执行完毕或者发生异常时,需要关闭所有打开的浏览器窗口,停止驱动程序,并释放资源时使用。 - driver.close():当测试用例需要多次打开浏览器并且每次执行后需要关闭当前打开的浏览器窗口并继续执行后续操作时使用。 3. 关闭浏览器窗口的效果 - driver.quit():关闭所有浏览器窗口,相当于手动关闭浏览器。 - driver.close():只关闭当前浏览器窗口,若当前浏览器窗口是最后一个打开的窗口,则相当于手动关闭浏览器。 4. 释放资源 - driver.quit():停止驱动程序,释放所有资源(包括 chromedriver.exe、geckodriver.exe 等)。 - driver.close():只关闭当前浏览器窗口,但驱动程序仍在运行,未释放相关资源。 综上所述,driver.quit() 和 driver.close() 方法虽然都可以用于关闭浏览器窗口,但其应用场景和效果略有不同,具体使用需根据实际情况选择。 如果只是在当前用例执行中想要关闭当前窗口,可以选择使用driver.close()方法。但如果测试用例执行完毕或者发生异常,需要强制关闭浏览器,并释放资源,可以使用driver.quit()方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值