Thread的Interrupt、isInterrupted、interrupted

线程中断:Interrupt、isInterrupted、interrupted

线程并不是抢占式的,线程是协作式的。

  • Interrupt:声明此线程中断,但是线程并不会立即中断;

  • isInterrupted:判断此线程是否已中断,判断完后不修改线程的中断状态;

  • interrupted:判断此线程是否已中断,判断完后清除线程的中断状态

线程的中断状态默认为( isInterrupted=false interrupted=false ),也就是默认不中断线程

Interrupt理解:

中断线程(isInterrupted=true)

就比如皇上(线程)每晚挑选一个妃子侍寝,到了时间,太监会告诉皇上(线程),时间到了(声明线程中断),皇上(线程)知道了,但是动作停不停还是皇上(线程)说了算,可以不理会,也可以收手。

isInterrupted理解:

判断是否中断线程,如果(isInterrupted=true)则可以控制皇上(线程)收手(停止);皇上(线程)收手(停止)后,线程还是中断状态,也就是(isInterrupted=true);

interrupted理解:

判断是否中断线程,如果(interrupted=true)则可以控制皇上(线程)收手(停止);皇上(线程)收手(停止)后,线程会清楚中断状态,也就是(isInterrupted=false);

测试代码

public class TheadInterrupt {

    //线程继承Thread类
    private static class UserThread extends Thread{
        public UserThread(String name){
            super(name);
        }
        @Override
        public void run() {
            String threadName = Thread.currentThread().getName();
            System.out.println(threadName+"Thread=start=interrupt:"+isInterrupted());
            //测试线程中断
            while (!isInterrupted()){//打开测试isInterrupted
            //while (!interrupted()){//打开测试interrupted
                System.out.println(threadName+"Thread=while=interrupt:"+isInterrupted());
            }
            System.out.println(threadName+"Thread=end=interrupt:"+isInterrupted());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        UserThread userThread = new UserThread("mjtabu");
        userThread.start();
        //线程睡眠 n 毫秒(时间可调)
        userThread.sleep(2);
        //睡眠 n 毫秒后线程中断
        userThread.interrupt();
    }
}

isInterrupted 测试运行结果:

interrupted 测试运行结果:

猜你喜欢

转载自www.cnblogs.com/mjtabu/p/12694964.html