Home » Java Thread interrupt() Method with Examples

Java Thread interrupt() Method with Examples

by Online Tutorials Library

Java Thread interrupt() method

The interrupt() method of thread class is used to interrupt the thread. If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked) then using the interrupt() method, we can interrupt the thread execution by throwing InterruptedException.

If the thread is not in the sleeping or waiting state then calling the interrupt() method performs a normal behavior and doesn’t interrupt the thread but sets the interrupt flag to true.

Syntax

Return

This method does not return any value.

Exception

SecurityException: This exception throws if the current thread cannot modify the thread.

Example 1: Interrupting a thread that stops working

In this program, after interrupting the thread, we throw a new exception so it will stop working.

Test it Now

Output:

Exception in thread "Thread-0" java.lang.RuntimeException: Thread interrupted...java.lang.InterruptedException: sleep interrupted  at JavaInterruptExp1.run(JavaInterruptExp1.java:10)  

Example 2: Interrupting a thread that doesn’t stop working

In this example, after interrupting the thread, we handle the exception, so it will break out from the sleeping state but will not stop working.

Test it Now

Output:

Exception handled java.lang.InterruptedException: sleep interrupted  thread is running...  

Example 3: Interrupting a thread that behaves normally

In this program, there is no exception occurred during the thread execution. Here, interrupt() method only sets the interrupted flag to true that can be used to stop the thread by the Java programmer later.

Test it Now

Output:

1  2  3  4  5  

Next TopicJava Thread

You may also like