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多線程學習之異常停止方法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.