package learn.thread;
/*
* 线程停止方法方法 -异常停止法
*/
public class Demo5 extends Thread {
public Demo5(String name) {
super(name);
}
String name;
@Override
public void run() {
try {
for (int i = 0; i < 500000; i++) {
if (this.isInterrupted()) {
System.out.println("已经是停止状态");
throw new InterruptedException();
}
System.out.println("i: " + (i + 1));
}
System.out.println("我是他后面的代码,表示线程没有立即停止");
} catch (InterruptedException e) {
System.out.println("进入run方法的catch");
e.printStackTrace();
}
}
public static void main(String[] args) {
Demo5 t1 = new Demo5("A");
t1.start();
try {
Thread.sleep(1000);
System.out.println("线程是否中止状态: " + t1.isInterrupted());
// 标记线程中断方法
t1.interrupt();
System.out.println("线程是否中止状态: " + t1.isInterrupted());
} catch (InterruptedException e) {
System.out.println("进入catch");
e.printStackTrace();
}
System.out.println("end");
}
}
java多线程学习之异常停止方法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.