方法调用过程中有嵌套调用方法,两个方法中都会出现InterruptedException异常,并且方法中有循环,要让InterruptedException能够正常捕获,需要特殊注意和break的搭配。
public void test1() throws InterruptedException {
for (int i = 0; i < 10; i++) {
try {
int rs = test2();
System.out.println(rs);
Thread.sleep(100);
} catch (InterruptedException e) {
throw e;
}
}
}
public int test2() throws InterruptedException {
for (int i = 0; i < 20; i++) {
try {
if (i == 10) {
break;
}
if (i == 5) {
return i;
}
Thread.sleep(100);
} catch (InterruptedException e) {
throw e;
}
}
return -1;
}
如果在test2中循环发生着,并且刚好执行到满足break条件进去,此时本线程挂起,而且此时别的线程让该线程的interrupted()值为true。要然程序能够抛出InterruptedException必须在break之前调用interrupted()判断方法是否要抛出InterruptedException,如果要要在这里主动抛出,不然方法结束。interrupted()的值就变为false,return不会影响。
正确下方如下:
public void test1() throws InterruptedException {
for (int i = 0; i < 10; i++) {
try {
int rs = test2();
System.out.println(rs);
Thread.sleep(100);
} catch (InterruptedException e) {
throw e;
}
}
}
public int test2() throws InterruptedException {
for (int i = 0; i < 20; i++) {
try {
if (i == 10) {
if (Thread.interrupted()) {
throw new InterruptedException();
}
break;
}
if (i == 5) {
return i;
}
Thread.sleep(100);
} catch (InterruptedException e) {
throw e;
}
}
return -1;
}