这是java多线程编程核心技术上的事例,书上是把try写在for循环外面,能够捕获到
异常,但我把try写到for里面后,发现捕获不到异常
public class MyThread extends Thread {
/*@Override
public void run() {
try {
for (int i = 0; i < 500000; i++) {
if (this.interrupted()) {
System.out.println("已经是停止状态了!我要退出了!");
throw new InterruptedException();
}
System.out.println("i=" + (i + 1));
}
} catch (InterruptedException e) {
System.out.println("catch interruted exception");
e.printStackTrace();
}
}*/
public void run() {
for (int i = 0; i < 500000; i++) {
try {
if (this.interrupted()) {
System.out.println("已经是停止状态了!我要退出了!");
throw new InterruptedException();
}
System.out.println("i=" + (i + 1));
} catch (InterruptedException e) {
System.out.println("catch interruted exception");
e.printStackTrace();
}
}
}
public static void main(String[] args) {
try {
MyThread t = new MyThread();
t.start();
Thread.sleep(2000);
t.interrupt();
} catch (InterruptedException e) {
System.out.println("主线程被捕获");
e.printStackTrace();
}
}
}