java.lang.Thread.interrupted()%uA0方法中断这个线程。测试是否当前线程已被中断。
如果这个方法被连续调用两次,第二次调用将返回false(除非当前线程再次中断,之后在第一次调用已清除了其中断状态和第二次调用已审查之前)。
声明
以下是java.lang.Thread.interrupted()方法的声明
public static boolean interrupted()
参数
-
NA
返回值
如果当前线程已经中断此方法返回true否则为false。
异常
-
NA
例子
下面的例子显示java.lang.Thread.interrupted()方法的使用。
package com.yiibai 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() // interrupt the threads if (!t.interrupted()) { 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