首頁 >Java >java教程 >如何在Java中中斷正在執行的執行緒?

如何在Java中中斷正在執行的執行緒?

WBOY
WBOY轉載
2023-09-18 13:49:02891瀏覽

如何在Java中中斷正在執行的執行緒?

執行緒可以透過呼叫執行緒物件的 interrupt() 方法來傳送中斷訊號,從而中斷執行緒。這意味著線程的中斷是由其他執行緒呼叫 interrupt() 方法引起的。

Thread 類別提供了三個中斷方法:

  • void interrupt() - 中斷執行緒。
  • static boolean interrupted() - 測試目前執行緒是否被中斷。
  • boolean isInterrupted() - 測試執行緒是否被中斷。

範例

public class ThreadInterruptTest {
   public static void main(String[] args) {
      System.out.println("Thread main started");
      final Task task = new Task();
      final Thread thread = new Thread(task);
      thread.start();
      thread.interrupt(); // calling interrupt()<strong> </strong>method
      System.out.println("Main Thread finished");
   }
}
class Task implements Runnable {
   @Override
   public void run() {
      for (int i = 0; i < 5; i++) {
         System.out.println("[" + Thread.currentThread().getName() + "] Message " + i);
         if(Thread.interrupted()) {
            System.out.println("This thread was interruped by someone calling this Thread.interrupt()");
            System.out.println("Cancelling task running in thread " + Thread.currentThread().getName());
            System.out.println("After Thread.interrupted() call, JVM reset the interrupted value to: " + Thread.interrupted());
            break;
         }
      }
   }
}

輸出

Thread main started
Main Thread finished
[Thread-0] Message 0
This thread was interruped by someone calling this Thread.interrupt()
Cancelling task running in thread Thread-0
After Thread.interrupted() call, JVM reset the interrupted value to: false

以上是如何在Java中中斷正在執行的執行緒?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除