线程停止有四种种情况:
1.run运行结束
2.异常退出
3.stop强制中止,这个不推荐使用,存在风险,比如说扫尾清理工作未完成,关闭资源未完成 就退出了。
4.interrupt方法中断线程, 需要主动编码配合,写中断逻辑,但是可控。
调用interrupt()方法只是打了个退出标志,并非真正的退出,退出逻辑需要自己写。
package ThreadCheat1.interrupt;
/**
* @ClassName InterruptDemo
* @Author laixiaoxing
* @Date 2019/4/22 下午12:35
* @Description 验证中断
* @Version 1.0
*/
public class InterruptDemo {
static class Mythread implements Runnable{
@Override
public void run() {
for (int i = 0; i <500000 ; i++) {
System.out.println("i="+(i+1));
}
}
}
public static void main(String[] args) {
Mythread mythread=new Mythread();
Thread thread=new Thread(mythread);
thread.start();
try {
Thread.sleep(2000);
thread.interrupt();
} catch (InterruptedException e) {
System.out.println("main catch");
e.printStackTrace();
}
}
}
<

线程停止包括run结束、异常退出、stop强制中止(不推荐)和interrupt方法中断。interrupt()仅设置中断标志,需配合中断逻辑。this.interrupted()会清除中断状态,isInterrupted()则不。建议在代码中通过interrupted判断并抛出中断异常来控制线程停止,以实现更可控的中断操作。避免使用stop方法,因为它可能造成资源未释放的问题。
最低0.47元/天 解锁文章
1578

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



