Java.Multithreading.How to stop a thread?

❌ Deprecated (DO NOT USE)

thread.stop();    // 🚫 Dangerous and deprecated

This kills the thread immediately — which can leave shared data in an inconsistent state.

It doesn’t give the thread a chance to clean up resources or release locks.

✅ Correct Way: Use a Stop Flag

This is the standard and safest way: the thread checks a volatile flag regularly and exits when it’s told to stop.

🔁 Example:

class MyTask implements Runnable {
    private volatile boolean running = true;

    public void run() {
        while (running) {
            System.out.println("Thread is working...");
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // Handle interrupt if needed
                System.out.println("Thread was interrupted during sleep");
                break;
            }
        }
        System.out.println("Thread stopped.");
    }

    public void stop() {
        running = false;
    }
}

Usage:

MyTask task = new MyTask();
Thread t = new Thread(task);
t.start();

// Stop after 2 seconds
Thread.sleep(2000);
task.stop(); // Signals the thread to exit gracefully

✅ Option 2: Interrupt the Thread

If the thread is doing blocking work (e.g. sleep(), wait(), or join()), use Thread.interrupt().

Example:

Thread t = new Thread(() -> {
    try {
        while (!Thread.currentThread().isInterrupted()) {
            System.out.println("Running...");
            Thread.sleep(1000); // Will throw InterruptedException
        }
    } catch (InterruptedException e) {
        System.out.println("Thread interrupted, exiting...");
    }
});
t.start();

// Stop it after 3 seconds
Thread.sleep(3000);
t.interrupt(); // Wakes it up from sleep

✅ Summary of Thread Stopping Techniques

MethodSafe?Use Case
stop()❌ No🚫 Don’t use — deprecated
volatile flag✅ YesLooping tasks, polling regularly
interrupt()✅ YesBlocking calls (sleep(), wait(), join() etc.)
ExecutorService.shutdown()✅ YesThread pools and background services

🔐 Best Practice

  • Always design threads to exit on request.
  • Combine volatile + interrupt() if needed.
  • Never forcefully stop a thread — think graceful shutdown.
This entry was posted in Без рубрики. Bookmark the permalink.