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.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(); // 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