在主线程的handler里开子线程 主线程会卡主

实现一个在2s双击返回键就退出程序的功能,将延迟放到了handler中。

public void onBackPressed() {
        Log.i("isfinish",""+is_Finish);
        if(is_Finish == 0){
            Toast.makeText(this,"再按一次返回键退出",Toast.LENGTH_SHORT).show();
            is_Finish = 1;
            Message msg = new Message();
            msg.what = FINISH;
            handler.sendMessage(msg);
        }else{
            finish();
        }
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    try {
                        Thread thread = new Thread();
                        thread.sleep(2000);
                        is_Finish = 0;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }
    };

实验时发现按下返回键后,进程将会卡主直到2s后即handler中thread休眠完才可以操作。

原因是在主线程中启用handler,handler中的looper是主线程的looper,在handler中使用Thread.sleep(1000),也就是相当于在主线程中延迟1000S所以当然会卡顿。

解决方法:使用HandlerThread

handlerThread使用

handler理解

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值