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

Ngắt (interrupt) một thread đang chạy trong Java

Cơ chế interrupt

Thread khác gọi thread.interrupt() → đặt cờ interrupted của thread mục tiêu = true. Thread bị ngắt phải tự kiểm tra cờ này (qua Thread.interrupted() hoặc isInterrupted()) và quyết định dừng.

3 phương thức liên quan

  • void interrupt() – gửi yêu cầu ngắt (instance method)
  • static boolean interrupted() – kiểm tra & xóa cờ interrupted của thread hiện tại
  • boolean isInterrupted() – kiểm tra cờ interrupted của thread này không xóa

Ví dụ: Thread tự kiểm tra cờ và dừng


public class ThreadInterruptDemo {
    public static void main(String[] args) {
        System.out.println("Main thread started");
        Task task = new Task();
        Thread thread = new Thread(task);
        thread.start();

        thread.interrupt(); // Gửi interrupt
        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);

            // Kiểm tra cờ interrupted (static method) – cũng xóa cờ
            if (Thread.interrupted()) {
                System.out.println("Thread này bị ngắt bởi thread khác gọi interrupt()");
                System.out.println("Hủy task đang chạy trong " + Thread.currentThread().getName());
                System.out.println("Sau Thread.interrupted(), cờ bị reset: " + Thread.interrupted());
                break; // Thoát vòng lặp, kết thúc thread
            }
        }
    }
}

Kết quả (có thể khác nhau do scheduling)

Main thread started
Main thread finished
[Thread-0] Message 0
Thread này bị ngắt bởi thread khác gọi interrupt()
Hủy task đang chạy trong Thread-0
Sau Thread.interrupted(), cờ bị reset: false

Lưu ý: Nếu thread bị block ở sleep(), wait(), join(), interrupt sẽ ném InterruptedException và xóa cờ. Luôn xử lý exception này đúng cách (thường là break/return).