Java Thread interrupt() methodThe 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. SyntaxReturnThis method does not return any value. ExceptionSecurityException: This exception throws if the current thread cannot modify the thread. Example 1: Interrupting a thread that stops workingIn this program, after interrupting the thread, we throw a new exception so it will stop working. Test it NowOutput: 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 workingIn 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 NowOutput: Exception handled java.lang.InterruptedException: sleep interrupted thread is running... Example 3: Interrupting a thread that behaves normallyIn 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 NowOutput: 1 2 3 4 5 Next TopicJava Thread |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India