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

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

Thread类提供了三种中断方法

  • void-interrupt() 中断线程。

  • static boolean-interrupted()测试当前线程是否已被中断。

  • 布尔值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