Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Làm thế nào một luồng có thể ngắt quãng luồng khác trong Java?


Hàm interrupt trong Java dùng để ngắt thực thi luồng với ngoại lệ InterruptedException.

Ví dụ dưới đây cho thấy luồng đang thực thi dừng lại (do ngoại lệ mới ném trong catch block) sau khi bị ngắt:

Ví dụ

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");       }    } }

Kết quả

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)

Lớp Demo extends Thread. Trong khối try, hàm run ngủ 150ms. Khối catch bắt ngoại lệ và ném RuntimeException. Trong main, thể hiện Demo được tạo, luồng bắt đầu bằng start. Trong try, thể hiện bị interrupt, trong catch in thông báo ngoại lệ.