首页  >  文章  >  Java  >  如何在Java中中断正在运行的线程?

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

WBOY
WBOY转载
2023-09-18 13:49:02850浏览

如何在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删除