Looper.quit方法

android src 4.0,Looper.java文件:

/**

* Run the message queue in this thread. Be sure to call quit() to end the loop

*/

public static void loop() {

    Looper me = myLooper();

    if (me == null) {

        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");

    }

    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();


    while (true) {

        Message msg = queue.next(); // might block

        if (msg != null) {

            if (msg.target == null) { // target为null,结束消息,结束循环

                // No target is a magic identifier for the quit message.

                return;

        }

    }

}


private Looper() {

    mQueue = new MessageQueue();

    mRun = true;

    mThread = Thread.currentThread();

}


public void quit() {

    Message msg = Message.obtain();

    // NOTE: By enqueueing directly into the message queue, the message is left with a null target. This is how we know it is a quit message

    // 发送一个target为null的消息,作为结束

    mQueue.enqueueMessage(msg, 0);

}


经测试,如果使用Looper.prepare()、Looper.loop()为Thread添加消息队列后,并启动thread;

               在不需要该thread中创建的Handler时,要调用looper.quit(),结束消息队列,进而结束线程。

               如果不这么做,thread会长时间存在不销毁。


前段时间,碰到一个问题:压力测试某个模块,一段时间后,总是crash,tombstones报的堆栈信息中,线程数量达上百个;排查后发现,是滥用HandlerThread导致的,把它等同与Thread来用了,使用完成后也没有调用quit进行销毁,导致线程数量一直在增加。


android 4.1.2 Looper.java:http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.1.2_r1/android/os/Looper.java#Looper.quit%28%29


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值