isInterrupted()
包java.lang.Thread.isInterrupted()中提供了此方法。
此方法用于检查线程是否已被中断。
此方法不是静态的,因此我们也无法使用类名访问此方法。
此方法的返回类型为boolean,因此如果线程已中断,则返回true;否则,如果线程未中断,则返回false。
我们需要记住,如果线程已中断,则此方法返回true,然后不像方法那样将标志设置为false interrupted()
。
此方法引发异常。
语法:
boolean isInterrupted(){ }
参数:
在Thread方法中,我们不传递任何对象作为参数。
返回值:
该方法的返回类型为boolean,返回true或false,并且如果线程已中断,则返回true,否则返回false。
isInterrupted()
方法示例/* We will use Thread class methods so we are importing the package but it is not mandate because it is imported by default */ import java.lang.Thread; class InterruptedThread extends Thread { //覆盖run() Thread类的方法 public void run() { for (int i = 0; i <= 3; ++i) { /* By using interrupted() method to check whether this thread has been interrupted or not it will return and execute the interrupted code */ 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(); /* By using start() method to call the run() method of Thread class and Thread class start() will call run() method of InterruptedThread class */ it2.start(); it2.interrupt(); it1.start(); } }
输出结果
E:\Programs>javac InterruptedThread.java E:\Programs>java InterruptedThread Is the thread Thread-1 has been interrupted: true Is the thread Thread-0 has been interrupted: false Is the thread Thread-1 has been interrupted: true Is the thread Thread-1 has been interrupted: true Is the thread Thread-0 has been interrupted: false Is the thread Thread-1 has been interrupted: true Is the thread Thread-0 has been interrupted: false Is the thread Thread-0 has been interrupted: false