Java中interrupted()和isInterrupted()之间的区别

interrupted()和isInterrupted()

在这里,我们将看到如何isInterrupted()不同于interrupted()在Java中?

isInterrupted()

  • 此方法在java.lang包中可用。

  • 这是非静态方法,因此可通过类对象访问此方法。

  • 此方法用于检查线程是否已被中断。

  • 此方法的返回类型为boolean,因此如果线程已中断,则返回true,否则返回false。

  • 对于isInterrupted()方法,我们需要注意的是,如果线程已被中断,则此方法返回true,然后在中断之后不再将布尔变量设置为false,就像interrupted()方法否则返回false一样。

  • 该方法的语法如下:

    public boolean isInterrupted(){
    }

示例

/*我们将使用Thread类方法,因此我们将导入包
但这不是强制性的,因为它是默认导入的
*/

import java.lang.Thread;

class InterruptedThread extends Thread {
    //覆盖run()  Thread类的方法
    public void run() {
        for (int i = 0; i <= 3; ++i) {

            /*  通过使用interrupted()方法检查此线程是否
            无论是否中断,它都将返回并执行
            中断的代码
            */
            if (Thread.currentThread().isInterrupted()) {
                System.out.println("Is the thread" + Thread.currentThread().getName() + "has been interrupted: " +  Thread.currentThread().isInterrupted());
            } else {
                System.out.println("Is the thread" + Thread.currentThread().getName() + "has been interrupted: " +  Thread.currentThread().isInterrupted());
                }
            }
        }
        public static void main(String args[]) {
            InterruptedThread it1 = new InterruptedThread();
            InterruptedThread it2 = new InterruptedThread();

            /*  使用start()方法调用Thread类的run()方法
            线程类start()将调用
            InterruptedThread类
            */
            it2.start();
            it2.interrupt();
            it1.start();
        }
    }

输出结果

E:\Programs>javac InterruptedThread.java
E:\Programs>java InterruptedThread
Is the threadThread-1 has been interrupted: true
Is the threadThread-0 has been interrupted: false
Is the threadThread-1 has been interrupted: true
Is the threadThread-1 has been interrupted: true
Is the threadThread-0 has been interrupted: false
Is the threadThread-1 has been interrupted: true
Is the threadThread-0 has been interrupted: false
Is the threadThread-0 has been interrupted: false

在这里,我们将看到如何interrupted()不同于isInterrupted()在Java中?