Java.lang.Thread.isInterrupted() 方法
描述
java.lang.Thread.isInterrupted() 方法测试该线程是否被中断。 线程的中断状态不受此方法影响。
由于在中断时线程不活动而被忽略的线程中断将通过此方法返回 false 来反映。
声明
以下是 java.lang.Thread.isInterrupted() 方法的声明。
public boolean isInterrupted()
参数
NA
返回值
如果此线程已被中断,则此方法返回 true; 否则为 false 。
异常
NA
示例
下面的例子展示了 java.lang.Thread.isInterrupted() 方法的使用。
package com.tutorialspoint;
import java.lang.*;
public class ThreadDemo implements Runnable {
Thread t;
ThreadDemo() {
t = new Thread(this);
System.out.println("Executing " + t.getName());
// this will call run() fucntion
t.start();
// tests whether this thread has been interrupted
if (!t.isInterrupted()) {
t.interrupt();
}
// block until other threads finish
try {
t.join();
} catch(InterruptedException e) {}
}
public void run() {
try {
while (true) {
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.print(t.getName() + " interrupted:");
System.out.println(e.toString());
}
}
public static void main(String args[]) {
new ThreadDemo();
new ThreadDemo();
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
Executing Thread-0 Thread-0 interrupted:java.lang.InterruptedException: sleep interrupted Executing Thread-1 Thread-1 interrupted:java.lang.InterruptedException: sleep interrupted

