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

Dừng thread trong Java (stop() deprecated)

Thread.stop() đã deprecated

Phương thức stop() bị deprecated từ Java 1.2 vì không an toàn (thread death, lock không được release, dữ liệu corrupt). Cách đúng: dùng cờ (flag) volatile hoặc interrupt() để thread tự dừng.

Ví dụ: Dùng flag volatile


public class ThreadStopDemo {
    public static void main(String[] args) throws InterruptedException {
        UserThread userThread = new UserThread();
        Thread thread = new Thread(userThread, "T1");
        thread.start();

        System.out.println(Thread.currentThread().getName() + " đang dừng user thread");
        userThread.stop(); // Gọi method custom stop()
        Thread.sleep(2000);
        System.out.println(Thread.currentThread().getName() + " kết thúc");
    }
}

class UserThread implements Runnable {
    private volatile boolean exit = false; // volatile đảm bảo visibility

    public void run() {
        while (!exit) {
            System.out.println("User thread đang chạy...");
            try { Thread.sleep(500); } catch (InterruptedException ignored) {}
        }
        System.out.println("User thread đã dừng");
    }

    public void stop() { // method tùy chỉnh, không phải Thread.stop()
        exit = true;
    }
}

Kết quả

main đang dừng user thread
User thread đang chạy...
User thread đã dừng
main kết thúc

Cách khác: dùng interrupt()


thread.interrupt(); // trong main
// Trong run():
while (!Thread.currentThread().isInterrupted()) { ... }
// Hoặc catch InterruptedException khi sleep/wait

Best practice: Không bao giờ dùng Thread.stop(), suspend(), resume(). Dùng flag volatile hoặc interrupt pattern.