public class MyThread extends Thread{
@Override
public void run() {
super.run();
try{
for (int i = 0; i < 500000; i++) {
//通过 interrupted 方法是测试 当前线程 是否已经是中断状态
// (该方法是Thread类的静态方法,执行后会将状态标识清除为false的功能)
//另一个 isInterrupted 方法是测试 线程Thread对象 是否已经是中断状态,
// 执行后不清除状态标识
if(this.interrupted()){
System.out.println("在for中退出,并抛出异常");
throw new InterruptedException();
}
System.out.println("i:"+i);
}
System.out.println("for下面");
}catch (InterruptedException e){
System.out.println("进入 MyThread catch 异常块");
e.printStackTrace();
}
}
}
public class RunThread {
public static void main(String[] args) {
try{
MyThread myThread = new MyThread();
myThread.start();
//先让main线程睡眠一段时间,保证线程mythread能运行一会儿
Thread.sleep(200);
//在myThread线程之后一段时间后,调用interrupt方法,将myThread的状态标识为false
//这时,myThread就会抛出异常
myThread.interrupt();
}catch (InterruptedException e){
//由于线程main和线程myThread是异步执行的,所以在myThread抛出异常时,
// main已经执行完毕了,所以没有执行这个catch块和最下面的sout
System.out.println("进入main catch 异常块");
e.printStackTrace();
}
System.out.println("end main");
}
}
运行结果(main线程睡眠期间,myThread运行一段时间,然后main线程中将myThread状态标识为true,此时myThread线程判断标识为true,则抛出异常,进入catch,在myThread抛出异常期间,由于main和myThread是异步的,所以main在抛出异常之前就已经执行完毕了)