Sobes.tech
Junior — Middle

How to properly shut down threads in a program?

sobes.tech AI

Answer from AI

Proper termination of threads in Java includes:

  • Using the interrupt flag to notify the thread about the need to terminate.
  • Regularly checking the interrupt status within the thread using Thread.currentThread().isInterrupted() and terminating gracefully.
  • Handling InterruptedException in threads that wait or sleep.
  • Using shutdown() and shutdownNow() methods of ExecutorService for proper thread pool termination.

Example with thread interruption:

class MyRunnable implements Runnable {
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            // thread work
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // restore interrupt flag
                break;
            }
        }
        // resource cleanup before exit
    }
}

// Starting and stopping
Thread thread = new Thread(new MyRunnable());
thread.start();
// ...
thread.interrupt(); // request termination
How to properly shut down threads in a program? — Java - sobes.tech