如何在 Java 中中断正在运行的线程?

javaobject oriented programmingprogramming更新于 2025/6/30 20:28:17

线程可以通过在 Thread  对象上调用中断来发送中断,以便中断线程。这意味着线程的中断是由任何其他线程调用 interrupt() 方法引起的。

Thread 类提供三种中断方法

  • void break() - 中断线程。
  • 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() 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

相关文章


有用资源