Sobes.tech
Middle

How can you stop a thread in Java?

sobes.tech AI

Answer from AI

In Java, there is no standard way to "stop" a thread from outside, like in older versions with Thread.stop(), which is deprecated due to safety concerns (it could lead to data corruption). Instead, cooperative approaches are used:

  1. Using a flag: A boolean flag is created in the thread, which is checked periodically. External code changes the flag's value, and the thread finishes its work.

    // Thread class
    class MyRunnable implements Runnable {
        private volatile boolean running = true; // volatile for visibility of changes
    
        public void run() {
            while (running) {
                // Thread execution logic
                try {
                    Thread.sleep(100); // Example of simulating work
                } catch (InterruptedException e) {
                    // Handle interruption, possibly set running = false;
                    Thread.currentThread().interrupt(); // Restore interrupt status
                }
            }
        }
    
        public void stopRunning() {
            running = false;
        }
    }
    
    // Usage
    // MyRunnable task = new MyRunnable();
    // Thread thread = new Thread(task);
    // thread.start();
    // ...
    // task.stopRunning(); // Signal to stop
    
  2. Interrupt (interrupt()): Calling thread.interrupt() sets the thread's interrupt flag. The thread must check this flag (Thread.currentThread().isInterrupted()) and stop working. Blocking methods (like sleep(), wait(), join(), I/O methods) throw InterruptedException when interrupted.

    // Thread class
    class InterruptibleRunnable implements Runnable {
        public void run() {
            while (!Thread.currentThread().isInterrupted()) { // Check interrupt flag
                // Thread execution logic
                try {
                    Thread.sleep(100); // Example of simulating work
                } catch (InterruptedException e) {
                    // Thread was interrupted during sleep()
                    // Exit loop
                    Thread.currentThread().interrupt(); // Restore interrupt status if needed
                    break;
                }
            }
        }
    }
    
    // Usage
    // InterruptibleRunnable task = new InterruptibleRunnable();
    // Thread thread = new Thread(task);
    // thread.start();
    // ...
    // thread.interrupt(); // Request to interrupt
    

It is important to understand that both methods require active participation from the code running in the thread. The thread should periodically check the flag or interrupt status and handle stop signals properly.

How can you stop a thread in Java? — Java - sobes.tech