线程被中断后的执行

Execution of a thread after it got interrupted

线程正在执行打印从 0 到 n 的数字的任务,并在每个打印语句后休眠 4000 毫秒。中间线程的某个地方被打断了。现在,当同一个线程开始执行时,它将从哪里开始,它会再次开始打印从 0 到 n 的数字,还是从它被中断的地方打印数字。 这两种情况的原因是什么以及如何处理?


public class Main {

    public static void main(String[] args) throws InterruptedException {
   
        SleepTest sleepTest = new SleepTest();
        Thread thread = new Thread(sleepTest);
        thread.start();
        thread.interrupt();

    }
}
public class SleepTest implements Runnable{
static int sleep = 10;
    public void run(){
        for (int i =0; i<10; i++){
           System.out.println(i);

            try {
                Thread.currentThread().interrupt();
              Thread.sleep(4000);

            } catch (InterruptedException exception) {

                exception.printStackTrace();

            }
            System.out.println(Thread.interrupted());
        }
    }

Thread.currentThread().interrupt() 所做的只是将字段 interrupted 的值更新为 true

让我们看看程序的流程以及如何为 interrupted 字段赋值:


    public class Main {
    
        public static void main(String[] args) throws InterruptedException {
       
            SleepTest sleepTest = new SleepTest();
            Thread thread = new Thread(sleepTest, "Sub Thread"); // Give a name to this thread
            thread.start(); // main thread spawns the "Sub Thread". Value of "interrupted" - false
            thread.interrupt(); // called by main thread. Value of "interrupted" - true
    
        }
    }
    public class SleepTest implements Runnable{
        static int sleep = 10;
        public void run(){
            System.out.println(Thread.currentThread().getName()+" "+Thread.interrupted()); // prints "Sub Thread true"
            for (int i =0; i<10; i++){
               System.out.println(i);
    
                try {
                  Thread.currentThread().interrupt(); // no matter what value is for interrupted, it is assigned the value "true"
                  Thread.sleep(4000); // Can't call sleep with a "true" interrupted status. Exception is thrown. Note that, when the exception is thrown, the value of interrupted is "reset", i.e., set to false
    
                } catch (InterruptedException exception) {
    
                    exception.printStackTrace(); // whatever
    
                }
                System.out.println(Thread.interrupted()); // returns the value of interrupted and resets it to false
            }
        }

回答

where will it start from , will it start printing the numbers from 0 to n again, or it will print numbers from where it got interrupted.

调用中断不会导致它重新开始,因为它在此调用中所做的只是将值 interrupted 设置为 false(并且不修改任何其他内容)。

在线程对象上调用 interrupt() 只能建议线程停止。不能保证线程会停止。
完全取决于thread.run()方法的实现。

run() 的情况下,您正在捕获 InterruptedException 并且正在打印异常跟踪但没有停止线程。这就是为什么线程永远不会在 InterruptedException 上停止并继续执行的原因。
当看到控制台上的输出时,它可能看起来线程正在停止(通过查看异常跟踪)。

参考interrupt interrupted isinterrupted in Java