執行緒如何在 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”塊中,列印指示異常的相關訊息。
廣告