Run线程(阻塞线程) 如何关闭

不能使用 stop 方法 暴力关闭 线程


而要使用Interrupted()方法 但是这个方法并非真正的关闭线程了,而是做了一个中断标记 当调用isInterrupted() 值会发生改变。

但是这种思路是针对 非阻塞线程的, 对于阻塞线程(sleep wait )并不会 成功 ,而是会抛出个InterruptedException

阻塞线程 调用isAlive 方法 返回值也是False


所以我们的解决思路是:

1.调用 interrupted方法

2.对于阻塞线程就 catch Exception

//中断阻塞异常    抛异常 !!!
        lunborunnable=new Runnable() {
            @Override
            public void run() {
                  Boolean isrun=true;
                    try {
                        lunbothread.sleep(1500);

                        while (isrun) {
                            Log.d("homeview","::"+lunbothread.currentThread().isInterrupted());
                            if (lunbothread.currentThread().isInterrupted()) {
                                return;
                            }

                            if (handler != null) {
                                try {
                                    lunbothread.sleep(2000);
                                    Message lunbo_ms = handler.obtainMessage();
                                    lunbo_ms.what = 2;
                                    lunbo_ms.sendToTarget();

                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                    return;
                                }
                                Log.d("is execute?", "handler?");

                            } else {

                                Log.d("handlernull", "handler?");
                            }
                        }


                    } catch (InterruptedException e) {

                        e.printStackTrace();
                    }


            }
        };
        lunbothread=new Thread(lunborunnable);
         lunbothread.start();


interrupted方法
        if(homepagerView.lunbothread!=null){
            Log.d("lunbothread","main isinterrupted? :"+ homepagerView.lunbothread.isAlive());
            homepagerView.lunbothread.interrupt();
            Log.d("lunbothread","main isinterrupted? :"+homepagerView.lunbothread.isInterrupted());

        }
        else {
            Log.d("lunbothread","null");
        }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值