Home  >  Article  >  Java  >  Java InterruptedException

Java InterruptedException

WBOY
WBOYOriginal
2024-08-30 16:15:01927browse

InterruptedException occurs when a thread might be sleeping, waiting, or is occupied and interrupted before or at the time of some activity being executed. Sometimes a method might want to test whether a current thread has been interrupted or not. If it has been interrupted, then it will be throwing an exception immediately. Otherwise, it will be working the way it was working. In this topic, we are going to learn about Java InterruptedException.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax

In order to use the exception, you have to use the following syntax:

if (Thread.interrupted ())  // Clears interrupted status!
throw new InterruptedException ();

Here the method InterruptedException () creates an InterruptedException with no detailed message in it as a parameter.

But if it is thrown like InterruptedException (String s), it creates an InterruptedException with some specific detail. In this method, s is the detailed message.

How InterruptedException work in Java?

Here we will discuss the workflow of InterruptedException. Here in multi-threaded code, threads can often block; the thread pauses execution until some external condition is met, such as:

  • when a lock is released
  • or another thread completes an operation
  • and also, some I/O operation completes

Over here, threads can be interrupted. When an interrupt occurs, it stops the thread from doing the regular kind of work they are doing. But the exact response to the specified interrupt depends upon the thread’s state and then how the thread will be implemented as below:

We will have a thread that can be used to block threads or earlier threads that were present. When this is caught, it throws the InterruptedException. If there is no issue and there is no earlier thread, then the thread continues with its work. When the thread comes across an exception, it sets the thread’s interrupted status to true. The thread will poll to the method checkInterrupted () at regular intervals. This is the preferred way in which the thread is expected to work. Once the process is completed, then there is a cleanup activity that takes place. After clean up, the execution is then stopped. It throws the InterruptedException, if any and if not, it continues with its normal flow of execution.

If there is an interruption in the above process, the process is not supposed to close the thread immediately. This is because it will be in the middle of some computation, which will always be happening and hence it must wait.

Constructors

Constructors are Java objects which help in initializing a newly created object or method. It is a Java instance that does not have any return type. As this is supposed to initialize the object, it has the same name as the class to which it belongs. As a result, whenever the object is called, constructors are called automatically and are initialized. Below is a constructor method.

InterruptedException ()

Here, this method creates an exception with no message in it. An instance of the InterruptedException class is being created over here. In this constructor, the message parameter is being set as null.

Example:

public InterruptedException () InterruptedException (String s)

In this method of InterruptedException class,  the parameter is being used as a specified message in the format of the string. Here the string parameter explains the name of the class that threw the error.

Example on InterruptedException

Now we will have a look at an example where a thread is being interrupted:

// Java Program to check how
// interrupt () method  works
// simultaneously while a thread stops working
class CheckInterruption extends Thread {
public void run ()
{
try {
Thread.sleep (2000);
System.out.println ( "We are checking Interrupted Exception");
}
catch (InterruptedException e) {
throw new RuntimeException ( "Thread is" + "interrupted");
}
}
public static void main (String args[])
{
CheckInterruption t1 = new CheckInterruption ();
t1.start ();
try {
t1.interrupt ();
}
catch (Exception e) {
System.out.println ("Exception handled");
}
}
}

Output:

Java InterruptedException

The above code helps us in understanding the concept of Interrupted Exception. We have a class, CheckInterruption, which extends the Thread class of Java. It then looks for the exception in the try block. If there is an exception, it is caught in the catch block, and output is displayed as a catch block. This is the case in our example where the interruption is caught, and necessary output is displayed. But the program is not completed as the catch block calls the Exception () method present in Java. Let us now check an example where the exception is caught, and then the next thread starts.

class CheckInterruptingThread2 extends Thread{
public void run (){
try{  Thread.sleep (1000);
System.out.println ("task");
}catch (InterruptedException e){
System.out.println ("Exception is handled "+e);  }
System.out.println ("thread is now in running state...");
}
public static void main (String args[]){
CheckInterruptingThread2 t1=new CheckInterruptingThread2 ();
t1.start ();
t1.interrupt ();
}
}

Output:

Java InterruptedException

The above program uses a class that is again extending the Thread class in Java. In the try () block, we make the thread sleep for some time, and then the catch block catches the exception when it is encountered. Once it is handled, the message is printed, and then the interrupt () method is called, after which the next thread moves to the running state. The same is displayed after the method call is finished and the thread starts working.

How to avoid InterruptedException?

The solution to this exception is you can stop making use of thread.sleep () method. Instead of this method, the more efficient method will be SystemClock.sleep () method. Another replacement for the above-mentioned method can be using TimeCOunter, which will depend on the logic and code where it is being used. This can also be an optimal solution.

If at all you would still like to make use of thread.sleep () then it should be used as below.

try {
Thread.sleep ();
} catch (InterruptedException e) {
Thread.currentThread ().interrupt (); /* this line will see to it that Thread.interrupted () always returns true */
throw new RuntimeException (e);
}

Conclusion – Java InterruptedException

As the word exception suggests, it is a state which can be checked and allowed to pass in some cases. InterruptedException happens when a thread waits or sleeps, and other threads are interrupted and cannot proceed further. We can handle this exception by either using proper try-catch blocks or by avoiding the usage of the sleep () method.

The above is the detailed content of Java InterruptedException. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn