62,623
社区成员
发帖
与我相关
我的任务
分享
public class InterruptDemo {
public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1000);
System.out.println("I'm not interrupted!");
} catch (InterruptedException e) {
System.out.println("I'm interrupted!");
}
System.out.println("I'm back!");
}
});
thread1.start();
int delay = 400;
//int delay = 1400;
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
}
thread1.interrupt();
}
}
如果 delay = 400,打印结果是
I'm interrupted!
I'm back!
因为 InterruptedException 发生在 Thread.sleep(1000) 处,后面的 System.out.println("I'm not interrupted!") 被跳过,执行直接进入 catch 的部分。
如果 delay = 1400,打印结果是
I'm not interrupted!
I'm back!
因为在 Thread.sleep(1000)中,InterruptedException 没有发生。