java中的中断机制
阅读素材一:https://www.cnblogs.com/hapjin/p/5450779.html
阅读素材二:https://www.ibm.com/developerworks/cn/java/j-jtp05236.html
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("should be stopped and exit");
throw new InterruptedException();
}
System.out.println("i=" + (i + 1));
}
System.out.println("this line cannot be executed. cause thread throws exception");//这行语句不会被执行!!!
}catch(InterruptedException e){
System.out.println("catch interrupted exception");
e.printStackTrace();
}
}
}
当MyThread线程检测到中断标识为true后,在第9行抛出InterruptedException异常。这样,该线程就不能再执行其他的正常语句了(如,第13行语句不会执行)。这里表明:interrupt()方法有两个作用,一个是将线程的中断状态置位(中断状态由false变成true);另一个则是:让被中断的线程抛出InterruptedException异常。
这是很重要的。这样,对于那些阻塞方法(比如 wait() 和 sleep())而言,当另一个线程调用interrupt()中断该线程时,该线程会从阻塞状态退出并且抛出中断异常。这样,我们就可以捕捉到中断异常,并根据实际情况对该线程从阻塞方法中异常退出而进行一些处理。
比如说:线程A获得了锁进入了同步代码块中,但由于条件不足调用 wait() 方法阻塞了。这个时候,线程B执行 threadA.interrupt()请求中断线程A,此时线程A就会抛出InterruptedException,我们就可以在catch中捕获到这个异常并进行相应处理(比如进一步往上抛出)