Home Java Docker
Home     Java

Java Topic

What is Java
History of Java
Freature of Java
Difference Between Java & C++
Java Environment Set Up
Java Hello World Program & its Internal Process
Java Hello World Program
JDK, JRE and JVM
Java Variables
Java Data Types & Unicode System
Java Operators
Java Keywords
Java Control Statements
Java if else
Java switch
Java for loop
Java While loop
Java Do While loop
Java break
Java continue
Java Oops Concept
Java Object & Class
Java Method
Java Constructor
Java Static Keyword
Java this Keyword
Java Inheritance
Java Hybrid Inheritance
Aggregation(HAS-A)
Java Polymorphism
Java method overloading
Java method overriding
Java Runtime polymorphism
Java Dynamic Binding
Super keyword
Final keyword
Difference Between method overloading and method overriding
Java Abstraction
Java Interface
Abstract class vs Interface
Java Encapsulation
Java Package
Java Access Modifiers
covariant return type
Instance initializer block
Java instanceof operator
Object Cloning in Java
Wrapper classes in Java
Java Strictfp Keyword
Recursion in Java
Java Command Line Arguments
Difference between object and class
Java String
Java String Class
Java Immutable String
Java Immutable Class
String Buffer
String Builder
String Buffer vs String
String Builder vs String Buffer
String Tokenizer in Java
Java Array
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking vs Multithreading
Garbage Collection
RunTime Class
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java
Java Applet
Animation in Applet
EventHandling in Applet
Display image in Applet
Displaying Graphics in Applet
Parameter in Applet
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements

Interrupting a Thread in Java

  • In Java, interrupting threads can be a powerful technique to control their execution. By calling the interrupt() method on a thread, you can force it to exit the sleeping or waiting state and trigger an InterruptedException. When dealing with threads that are currently in a waiting or sleeping state as a result of methods like sleep() or wait() being called, this is especially helpful.

  • It is crucial to comprehend how the interrupt() method behaves in order to successfully interrupt a thread. An InterruptedException will be immediately thrown when this method is called on a thread that is waiting or sleeping, causing the thread to awaken and handle the exception. This enables the thread to take appropriate actions when interrupted, like cleaning up resources or terminating gracefully.

  • However, it is crucial to note that calling interrupt() on a thread not in a waiting or sleeping state will not forcibly stop its execution. Instead, the thread's interrupt flag will be set to true, enabling it to respond to the interruption later on in its execution. This can be particularly useful for threads that are performing lengthy computations or tasks and need to respond to the interruption at a convenient time.

  • To interrupt a sleeping or waiting thread, you can utilize the interrupt() method provided by the Thread class. The thread's current state will be effectively interrupted by this method, and it will throw an InterruptedException if the thread is stuck in a sleep() or wait() call.

  • In summary, interrupting threads in Java offers a powerful way to manage their execution and gracefully handle interruptions. By understanding the behavior of the interrupt() method and its effect on threads in different states, you can design more robust and responsive multi-threaded applications.





The Thread class provides three methods for interrupting a thread


  • public void interrupt()

  • public static boolean interrupted()

  • public boolean isInterrupted()

Example of Interrupting a thread that doesn't stop working

We handle the InterruptedException in the below program with a try and catch block, so that anytime another thread interrupts the presently operating thread, it would wake up but not stop functioning.

package DockerTpoint;
class ThreadClass extends Thread {
	public void run(){
		try{
			for (int i = 0; i < 3; i++) {
				System.out.println("ThreadClass Thread is running");
				 // The current thread is put to sleep, and another thread is given the opportunity to execute.
				Thread.sleep(1000);
			}
		}
		catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
class Main {
	public static void main(String[] args)throws InterruptedException{
		ThreadClass thread = new ThreadClass();
		thread.start();
		thread.interrupt();
		System.out.println("The main thread has finished its execution.");
	}
}





Output:

The main thread has finished its execution.
ThreadClass Thread is running
java.lang.InterruptedException: sleep interrupted 

Example of Interrupting a thread that stops working

In the program below, after interrupting the currently executing thread, we throw a new exception in the catch block, causing it to stop working.

package DockerTpoint;
class ThreadClass extends Thread {
	public void run(){
		try{
			Thread.sleep(1000);
			System.out.println("ThreadClass");
		}
		catch (InterruptedException e) {
			throw new RuntimeException("Thread interrupted"+e);  
		}
	}
}
class Main {
	public static void main(String[] args)throws InterruptedException{
		ThreadClass thread = new ThreadClass();
		thread.start();
		try {
			thread.interrupt();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}



Output:

Exception in thread "Thread-0" java.lang.RuntimeException: Thread 
    interruptedjava.lang.InterruptedException: sleep interrupted 

Example of Interrupting a thread that works normally

In the program below, after interrupting the currently executing thread, we throw a new exception in the catch block, causing it to stop working.

class ThreadClass extends Thread {
	public void run(){
		for (int i = 1; i <= 10; i++) {
			System.out.println("5 * "+i+" = "+5*i);
		}
	}
}
class Main {
	public static void main(String[] args){
		ThreadClass thread = new ThreadClass();
		thread.start();
		thread.interrupt();
	}
}



Output:

5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50 



Reentrant Monitor in Java Next »
« Perv Next »


Post your comment





Read Next Topic
Java Tutorial - Topic
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java

Read Other Java Chapter
Java Topic
Java Basic Tutorial
Java Control Statements
Java Classes & Object
Java Inheritance
Java Polymorphism
Java Abstraction
Java Encapsulation
Java OOPs Miscellaneous
Java Array
Java String
Java Exception Handling
Java Multithreading
Java Synchronization
Java Applet
Java 8 Features
Java 9 Features
Java Collection
Java Mcq
Java Interview Question
Tools
  

Useful Links

  • Home
  • Blog
  • About us
  • Contact Us
  • Privacy policy

Contact Us

Police Colony
Patna, Bihar
India

Email:

About DockerTpoint


India's largest site for Programming Tutorial as well as BANK, SSC, RAILWAY exam
and Campus placement preparation.