关于Java多线程-interrupt()、interrupted()、isInterrupted()解释

多线程先明白一个术语“中断状态”,中断状态为true,线程中断。

interrupt():就是通知中止线程的,使“中断状态”为true。

isInterrupted():就是打印中断状态的,然后不对中断状态有任何操作。

interrupted():检测运行这个方法的线程的中断状态,注意,是运行这个方法的线程,且会清除中断状态

   比如:新建了个对象MyThread,这个对象继承thread

public class MyThread extends Thread {
public MyThread(String name) {
        super(name);
    }
    @Override
    synchronized public void run() {

        for (int i = 0; i < 500000; i++) {
            System.out.println("i=" + i);
            if (isInterrupted()) {
                System.out.println("MyThread类-this.interrupted()= " + this.interrupted()
                        + ",Thread.currentThread().isInterrupted()= " + Thread.currentThread().isInterrupted());
                break;
            }
        }
    }
}

    在另外一个类比如叫Run类

public class Run {
    public static void main(String[] args) throws InterruptedException {
        MyThread m1 = new MyThread("A");
        m1.start();
        Thread.sleep(500);
        m1.interrupt();
        System.out.println("Run类-m1.interrupted()= " + m1.interrupted());
    }
}

    Run类的main方法里面new了一个MyThread类对象m1,

    调用m1的start()方法让m1先跑起来,

    然后调用m1的interrupt()方法,通知m1中断,此时m1中断状态为true,所以在m1中,isInterrupted()的值即中断状态为true,进入m1的打印方法里面,调用了interrupted()方法,这个就是重点,调用了interrupted()方法,先返回了中断状态true,然后把中断状态的值设置为false,所以再调用m1的isInterrupted()拿到的中断状态就为false了,

    现在回去Run类的main方法看一下,虽然在main方法中它明面上看是打印了m1的中断状态,但是实际上它打印的是main方法这个线程的中断状态,所以main方法线程的中断状态是false,对于这个

    官方解释:测试当前线程是否已经中断,当前线程是指运行 this.interrupted() 方法的线程

-------------------------------------------------看看文档解释:------------------------------------------------------

    

猜你喜欢

转载自www.cnblogs.com/convict/p/9693071.html
今日推荐