Java Thread isInterrupted() 方法



描述

Java Thread isInterrupted() 方法用於測試此執行緒是否已被中斷。執行緒的中斷狀態不受此方法影響。

如果執行緒在中斷時未處於活動狀態,則忽略的中斷將由此方法返回 false 來反映。

宣告

以下是 java.lang.Thread.isInterrupted() 方法的宣告

public boolean isInterrupted()

引數

返回值

如果此執行緒已被中斷,則此方法返回 true;否則返回 false。

異常

示例:檢查執行緒是否被中斷

以下示例演示了 Java Thread isInterrupted() 方法的使用。在此程式中,我們透過實現 Runnable 介面建立了一個執行緒類 ThreadDemo。在建構函式中,使用 new Thread 建立了一個新執行緒。它的名稱使用 getName() 列印,並使用 start() 方法啟動執行緒。使用 isInterrupted() 方法,我們檢查執行緒是否未被中斷,然後使用 interrupt() 方法中斷執行緒。然後,我們使用 join() 方法阻塞執行緒。在 run() 方法中,我們在 while(true) 迴圈中添加了 1 秒的休眠,這會導致 InterruptedException。

在 main 方法中,我們建立了兩個 ThreadDemo 執行緒。

package com.tutorialspoint;

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
java_lang_thread.htm
廣告