首页 > 解决方案 > 线程被中断后执行

问题描述

一个线程正在执行打印从 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());
        }
    }

标签: multithreadingthread-sleep

解决方案


所做的只是将字段的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
            }
        }

回答

它将从哪里开始,它会再次开始打印从 0 到 n 的数字,还是从中断的地方打印数字。

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


推荐阅读