java中有两个代码块。

区块一:

@Test
public void test1() {

    System.out.println("interrupt:" + Thread.currentThread().isInterrupted());
    Thread.currentThread().interrupt();
    System.out.println("interrupt:" + Thread.currentThread().isInterrupted());

}

输出:
interrupt:false
interrupt:true

区块二:
@Test
public void test2() throws InterruptedException {
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("running...");
        }
    });

    thread.interrupt();

    TimeUnit.SECONDS.sleep(2);

    System.out.println("interrupt:" + thread.isInterrupted());

    thread.start();

    TimeUnit.SECONDS.sleep(2);

    System.out.println("interrupt:" + thread.isInterrupted());

}

输出:
interrupt:false
running...
interrupt:false

所以,我的问题:
  • 为什么在调用 interrupt:true 后阻止一个打印 interrupt() 而阻止两个?
  • 调用interrupt()后JVM会做什么?

  • 谢谢!

    PS:区块三:
    @Test
    public void test3() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("running...");
            }
        });
    
        thread.interrupt();
    
        System.out.println("interrupt:" + thread.isInterrupted());
    
        // thread.start();
        //
        // thread.interrupt();
        //
        //
        // System.out.println("interrupt:" + thread.isInterrupted());
    
    }
    

    还输出:interrupt:false

    最佳答案

  • 在块 1 中,您中断自己,此“标记”具有中断标志的线程。
  • 在块 2 中,您中断其他线程(即不 Activity - 未启动 -)

  • 尝试在 run() 方法中添加 Thread.sleep(5000);并在中断之前开始;-)

    How interrupt works

    关于java - 我如何理解 Thread.interrupt()?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14182585/

    10-12 03:01