Sobes.tech
Junior — Middle

How can you interrupt the execution of a thread in a program?

sobes.tech AI

Answer from AI

In Android (and in Java in general), to interrupt the execution of a thread, you can use the interrupt() method of the Thread object. This method sets the interrupt flag for the thread, and if the thread is in a waiting state (for example, sleep(), wait()), an InterruptedException will be thrown.

To properly interrupt a thread, you should periodically check the interrupt status within its code using Thread.currentThread().isInterrupted() or catch InterruptedException.

Example:

Thread thread = new Thread(() -> {
    try {
        while (!Thread.currentThread().isInterrupted()) {
            // Perform work
            Thread.sleep(1000); // may throw InterruptedException
        }
    } catch (InterruptedException e) {
        // Thread was interrupted during sleep
        Thread.currentThread().interrupt(); // restore interrupt flag
    }
    // Finish work
});

thread.start();

// Interrupt the thread
thread.interrupt();

You can also use flags or other synchronization mechanisms for more controlled thread termination.

How can you interrupt the execution of a thread in a… - sobes.tech