isInterrupted()
/ interrupted()
).
InterruptedException
if blocked in
sleep()
, wait()
or join()
.
stop()
.Thread Interruption
related methods in the Thread
class:
public void interrupt()
sleep()
, wait()
or join()
, it will throw an InterruptedException
. true
, which the thread can check using isInterrupted()
or interrupted()
. public boolean isInterrupted()
public static boolean interrupted()
interrupt()
:
class MyThread1 extends Thread
{
public void run()
{
try
{
for (int i = 1; i <= 5; i++)
{
System.out.println(i); // Print the value of i
Thread.sleep(1000); // Sleep for 1 second
}
}
catch(InterruptedException e)
{
System.out.println("Thread Interrupted, stopping task gracefully...");
}
}
}
public class MainApp1
{
public static void main(String[] args)
{
MyThread1 t = new MyThread1(); // Create a new thread
t.start(); // Start the thread
t.interrupt(); // Interrupt the thread
}
}
1 Thread Interrupted, stopping task gracefully...
isInterrupted()
and interrupted()
:
class MyThread2 extends Thread
{
public void run()
{
// Interrupt the current thread manually
Thread.currentThread().interrupt();
// First check using interrupted() -> true, then resets flag
System.out.println("First check with interrupted(): " + Thread.interrupted());
// Second check using interrupted() -> false, because flag was cleared
System.out.println("Second check with interrupted(): " + Thread.interrupted());
// Now set interrupt flag again
Thread.currentThread().interrupt();
// Check with isInterrupted() -> true, does not reset flag
System.out.println("First check with isInterrupted(): " + Thread.currentThread().isInterrupted());
// Check again with isInterrupted() -> still true
System.out.println("Second check with isInterrupted(): " + Thread.currentThread().isInterrupted());
}
}
public class MainApp2
{
public static void main(String[] args)
{
MyThread2 mt = new MyThread2();
mt.start();
}
}
First check with interrupted(): true Second check with interrupted(): false First check with isInterrupted(): true Second check with isInterrupted(): true
interrupt()
on a thread does not forcibly stop it; it only sets the interrupt flag.sleep()
, wait()
, or join()
, it immediately throws an InterruptedException
.Thread.interrupted()
→ checks and clears the interrupt flag.isInterrupted()
→ checks the flag but does not clear it.stop()
method.InterruptedException
or checking the flag.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
We’re here to make our tutorials better based on your thoughts and suggestions.