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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cuizehui123/article/details/78267283

不能使用 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");
        }



猜你喜欢

转载自blog.csdn.net/cuizehui123/article/details/78267283