线程如何在 Java 中中断另一个线程?


在 Java 中可以使用“中断”函数,借助异常 InterruptedException 来中断线程执行。

以下示例展示了当前执行线程如何停止执行(这是因为在 catch 块中引发了新异常)一旦该线程中断 −

示例

 动态展示

public class Demo extends Thread
{
   public void run()
   {
      try
      {
         Thread.sleep(150);
         System.out.println("In the 'run' function inside try block");
      }
      catch (InterruptedException e)
      {
         throw new RuntimeException("The thread has been interrupted");
      }
   }
   public static void main(String args[])
   {
      Demo my_inst = new Demo();
      System.out.println("An instance of the Demo class has been created");
      my_inst.start();
      try
      {
         my_inst.interrupt();
      }
      catch (Exception e)
      {
         System.out.println("The exception has been handled");
      }
   }
}

输出

An instance of the Demo class has been created
Exception in thread "Thread-0" java.lang.RuntimeException: The thread has been interrupted
at Demo.run(Demo.java:12)

一个名为 Demo 的类扩展了 Thread 类。这里,在“try”块中,定义了一个名为“run”的函数,该函数使该函数休眠 150 毫秒。在“catch”块中,捕获异常并向控制台显示相关消息。

在 main 函数中,创建 Demo 类的实例,并使用“start”启动线程。在“try”块中,中断该实例,并在“catch”块中,打印指示异常的相关消息。

更新时间:13-7 月-2020

810 次浏览

启动你的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.