线程在两种情况下会终止:
- run()执行完毕
- run()执行中出现未捕获的异常
没有可以强制线程终止的方法,但可以使用interrupt方法请求终止。
当对一个线程调用interrupt方法时,线程的boolean标志位变为中断状态。通过检查该标志,可以判断该线程是否被中断,有两个检查方法:
- interrupted(): 判断是否中断,并清除中断状态
- isInterrupted(): 判断是否中断,不改变状态
一个被阻塞的线程(sleep、wait)不能检查中断状态,当对其调用interrupt(),会被Interrupted Exception异常中断。
异常法中断线程
public class MyThread extends Thread {
@Override
public void run() {
super.run();
try {
for (int i = 0; i < 500000; i++) {
if (this.interrupted()) {
System.out.println("停止了。");
throw new InterruptedException(); //之后的语句无法执行,return;同样能停止
}
System.out.println("i = " + ( i + 1 ));
}
} catch (InterruptedException e) {
System.out.println("被捕获了。");
e.printStackTrace();
}
}
}
public class Run {
public static void main(String[] args) {
try {
MyThread t = new MyThread();
t.start();
Thread.sleep(2000);
thread.interrupt();
} catch (InterruptedException e) {
System.out.println("被main捕获了。");
e.printStackTrace();
}
System.out.println("end.")
}
}
结果:
i = ...
停止了。
end.
被捕获了。