中断Interrupt

参考: https://www.cnblogs.com/lujiango/p/7641983.html
从下面的demo代码可以看出:
InterruptedException 被捕获的时候, 中断位会被重置.
interrupted 先返回当前中断位的状态, 然后重置
isInterrupted 对中断位没有影响
先决中断, 即在sleep, wait之前就触发的中断, 就后续的sleep等方法立刻退出, 并且抛出中断异常.

public class Main {
    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                while(true) {
                try {
                    System.out.println("interrupted status before sleep: " + Thread.currentThread().isInterrupted());
                    Thread.sleep(6000);
                    System.out.println("Yes, i  can sleep, really good!");
                } catch (InterruptedException i) {
                    System.out.println("interrupted exception happened");
                    var b = Thread.currentThread().isInterrupted();
                    System.out.println("thread1 interrupted?: " + b);
                    Thread.currentThread().interrupt();
                    System.out.println("after invoke interrupt(): " + Thread.currentThread().isInterrupted());

                }
                }

            }
        };
        var thread = new Thread(r);
        thread.start();

        Runnable i = new Runnable() {
            @Override
            public void run() {
              while(true) {
                try {
                    Thread.sleep(1000);
                    System.out.println("doing interrupt thread1");
                    thread.interrupt();
                } catch (InterruptedException i) {
                    System.out.println(Thread.currentThread().isInterrupted());

                }

              }
            }

        };
        var t2 = new Thread(i);
//        t2.start();


        try{
          Thread.sleep(1000);
        }catch(InterruptedException x) {
          System.out.println();
        }
        System.out.println("xxxxxxxxxxxxxxxx");
        thread.interrupt();


    }
}

你可能感兴趣的:(中断Interrupt)