Contents

Thread interrupt

Writen by: David Vlijmincx

Introduction

This post explains how to let a thread wait/sleep and how to interrupt a thread.

What about Stop, suspend, and resume?

In this post, I won't cover the stop, suspend en resume methods because they are deprecated, which means that they are no longer recommended for use and may not be supported in future versions of Java. Using deprecated methods can lead to problems and issues in your code, as they may not work as intended or may not work at all. Additionally, more up-to-date methods may be more efficient and effective than deprecated ones, so it is generally best to avoid them in favour of newer, better-supported alternatives. Therefore, to ensure that the information and guidance provided to you are current and relevant.

Interrupt

You can use the interrupted() method from the Thread class to interrupt a (running) thread. Calling this method sets the interrupt flag on the thread to true. You can use this flag inside your concurrent code to check if your thread has to stop.

If the thread you interrupt is sleeping using Thread.sleep() or waiting (yourThread.wait();), the thread immediately exits by throwing an InterruptedException.

In the following example, we have a main method that starts a thread and immediately interrupts the thread's sleep method call. The example code catches and throws a new runtime exception to the caller.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class ThreadTest {

    public static void main(String[] args) {

        Runnable task = () -> {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            // will not be printed
            System.out.println("print to the console");
        };

        Thread myThread = new Thread(task);

        myThread.start();

        myThread.interrupt();
        System.out.println("myThread = " + myThread);
    }
}

Catching the interruption

Catching and not throwing the exception will cause the thread to continue. It will not stop when the thread is interrupted. To immediately exit the thread, you would have to throw to exception again and not let the code swallow it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public static void main(String[] args) {

    Runnable task = () -> {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            System.out.println(" interrupted ");
        }
        // Will be printed to the console. The exception was swallowed
        System.out.println("print to the console");
    };

    Thread myThread = new Thread(task);

    myThread.start();

    myThread.interrupt();
    System.out.println("myThread = " + myThread);
}

Conclusion

In this post, We looked at how to interrupt a thread and if you swallow the exception inside a try-catch, the thread will continue to run.