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

หยุด Thread ใน Java

หยุด thread ด้วยเมธอด stop() ของคลาส Thread หยุดการทำงานและนำออกจาก waiting pool แล้วถูก Garbage Collected Thread จะจบอัตโนมัติเมื่อถึงท้ายเมธอด stop() ถูก deprecated เนื่องจากปัญหา Thread-safety

ไวยากรณ์

@Deprecated public final void stop()

ตัวอย่าง: หยุด Thread แบบปลอดภัย (ไม่ใช้ stop())


import static java.lang.Thread.currentThread;

public class ThreadStopTest {
    public static void main(String args[]) throws InterruptedException {
        UserThread userThread = new UserThread();
        Thread thread = new Thread(userThread, "T1");
        thread.start();
        System.out.println(currentThread().getName() + " is stopping user thread");
        userThread.stop(); // ใช้เมธอด custom stop()
        Thread.sleep(2000);
        System.out.println(currentThread().getName() + " is finished now");
    }
}

class UserThread implements Runnable {
    private volatile boolean exit = false;
    
    public void run() {
        while (!exit) {
            System.out.println("The user thread is running");
        }
        System.out.println("The user thread is now stopped");
    }
    
    public void stop() {
        exit = true; // ตั้ง flag ให้ loop หยุด
    }
}

ผลลัพธ์

main is stopping user thread
The user thread is running
The user thread is now stopped
main is finished now

แนวทางปฏิบัติที่ดี: ไม่ใช้ Thread.stop() ใช้ flag (volatile boolean) หรือ interrupt() ให้ thread ตรวจสอบและหยุดเอง (Graceful shutdown)