主线程睡眠/中断如何在以下代码中工作

Ara*_*asn 1 java multithreading sleep interrupt

第二个循环如何实际中断休眠的主线程,而第一个没有?我的理解是在Thread.sleep(3000)之后,代码Thread.currentThread().interrupt()会在3秒后执行。谁能解释它实际上是如何工作的

for (int i = 0; i < 2; i++) {
            try {
                System.out.println("loop : " + i);
                Thread.sleep(3000);
                System.out.println("Woke up");
                Thread.currentThread().interrupt();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
Run Code Online (Sandbox Code Playgroud)
loop : 0
Woke up
loop : 1
java.lang.InterruptedException: sleep interrupted
exception loop:1
    at java.base/java.lang.Thread.sleep(Native Method)
    at multithreadings.Mainclass.main(Mainclass.java:13)

Run Code Online (Sandbox Code Playgroud)

And*_*ner 5

中断是一种礼貌的停止请求:线程没有义务停止。

这就像罗宾威廉姆斯的笑话,当你犯罪时,英国警察会说些什么

停止!或者我会说再次停止!

此外,中断线程不会导致InterruptedException抛出an :它只是在线程上设置一个标志。如果某些东西(如Thread.sleep)检查此标志,并发现它已设置,则它可能会抛出一个InterruptedException; 但标志和异常是指示中断的两种正交方式。

像这样:

  • 在第一次执行时,您休眠 3 秒,然后设置中断标志,循环体正常完成。
  • 在第二次执行时,您要求休眠 3 秒,但Thread.sleep检测到中断标志并抛出异常。