Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Thread Interrupt ใน Java: หยุด Thread อีกตัวด้วย interrupt()

Thread.interrupt()

กลไกมาตรฐานสำหรับขอให้ thread หยุดทำงาน ไม่บังคับหยุดทันที แต่ตั้ง interrupt flag และปลุก thread ที่ blocked (sleep, wait, join, I/O)

ตัวอย่าง: Interrupt Thread ที่ Sleep


public class Demo extends Thread {
    @Override
    public void run() {
        try {
            System.out.println("Thread sleeping...");
            Thread.sleep(5000); // นอน 5 วินาที
            System.out.println("Woke up normally");
        } catch (InterruptedException e) {
            System.out.println("Interrupted! " + e.getMessage());
            // สำคัญ: restore interrupt flag หากต้องการส่งต่อ
            Thread.currentThread().interrupt();
        }
    }
    
    public static void main(String[] args) throws InterruptedException {
        Demo t = new Demo();
        t.start();
        
        Thread.sleep(100); // รอสักครู่
        System.out.println("Main: interrupting thread...");
        t.interrupt(); // ส่ง interrupt signal
        
        t.join(); // รอ thread จบ
        System.out.println("Main: done");
    }
}

ผลลัพธ์

Thread sleeping...
Main: interrupting thread...
Interrupted! sleep interrupted
Main: done

รูปแบบมาตรฐาน (Interrupt Pattern)


public void run() {
    while (!Thread.currentThread().isInterrupted()) {
        try {
            // ทำงานที่อาจ block
            Thread.sleep(100);
            // หรือ I/O, queue.take(), etc.
        } catch (InterruptedException e) {
            // ถูก interrupt ระหว่าง block
            Thread.currentThread().interrupt(); // restore flag
            break; // ออกจาก loop
        }
    }
    // cleanup ถ้าจำเป็น
}

เมธอดเกี่ยวกับ Interrupt

ข้อควรระวัง

  • Interrupt ไม่หยุด thread ทันที - ขึ้นอยู่กับโค้ดใน thread ว่าตรวจสอบ flag หรือ catch InterruptedException
  • Blocking methods (sleep, wait, join, I/O) โยน InterruptedException และ clear flag
  • Non-blocking code ต้องตรวจสอบ isInterrupted() เอง
  • ไม่ควรนिगา InterruptedException ไว้เงียบๆ - ควร restore flag หรือ throw ออกไป
Methodคำอธิบาย
interrupt()ส่ง interrupt signal ให้ thread นั้น
isInterrupted()ตรวจสอบ interrupt flag (ไม่ clear flag)
interrupted()static: ตรวจสอบ + clear flag ของ current thread