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

การหยุด Thread ใน Java อย่างปลอดภัย (Graceful Shutdown)

วิธีที่ถูกต้อง: ใช้ volatile flag

ไม่ควรใช้ Thread.stop(), Thread.suspend(), Thread.destroy() - deprecated และ unsafe (อาจ corrupt data, deadlock)

ตัวอย่าง: Graceful Shutdown ด้วย volatile boolean

public class Main {
    // volatile รับประกัน visibility ระหว่าง thread
    private static volatile boolean exit = false;
    
    public static void main(String[] args) throws InterruptedException {
        System.out.println("Starting main thread");
        
        Thread worker = new Thread(() -> {
            System.out.println("Worker thread started");
            while (!exit) {
                // ทำงานต่อไปจนกว่า exit จะเป็น true
                // ควรมีการ sleep/yield เล็กน้อยเพื่อไม่ให้ CPU 100%
                try { Thread.sleep(10); } catch (InterruptedException e) { break; }
            }
            System.out.println("Worker thread exiting gracefully");
        });
        
        worker.start();
        
        // Main thread ทำงานต่อ...
        Thread.sleep(100); // รอสักครู่
        
        // สั่งหยุด worker
        exit = true;
        System.out.println("Main thread requested shutdown");
        
        // รอ worker จบ (optional)
        worker.join();
        System.out.println("Main thread exiting");
    }
}

ผลลัพธ์

Starting main thread
Worker thread started
Main thread requested shutdown
Worker thread exiting gracefully
Main thread exiting

จุดสำคัญ

  • volatile รับประกันว่า thread อื่นจะเห็นค่าใหม่ทันที (visibility)
  • ตรวจสอบ flag ใน loop condition เป็นประจำ
  • ใช้ Thread.interrupt() + InterruptedException สำหรับ blocking operations (sleep, wait, I/O)
  • join() รอ thread จบทำงาน

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

while (!Thread.currentThread().isInterrupted()) {
    try {
        // blocking operation
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt(); // restore flag
        break;
    }
}