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

本文详细解析了Java中线程中断的正确实现方式,强调不应使用stop方法强行关闭线程,而应采用interrupt方法设置中断标志。文章通过具体实例展示了如何在运行中的线程中检查中断状态并优雅地退出,特别关注了阻塞线程如何处理InterruptedException。
647

被折叠的 条评论
为什么被折叠?



