Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – Interrupting a Thread

Java Programming Language interrupt Method in Multithreading

A thread can be interrupted explicitly by invoking an interrupt() method on it, but only if a thread is in sleeping or in waiting state. Otherwise, a thread will not get interrupted.
After invoking an interrupt() method on a thread, this method waits to interrupt a running thread until it gets into sleeping or waiting state.

Syntax of interrupt() method

public void interrupt()

Example

class ChildThread extends Thread
{
    public void run()
    {
        try
        {
            System.out.println("Child Thread Before Sleeping");
            Thread.sleep(100);
            System.out.println("Child Thread After Sleeping");
        }
        catch(InterruptedException e)
        {
            System.out.println("Child Thread Interrupted");
        }
    }
}

class InterruptDemo
{
    public static void main(String args[])
    {
        ChildThread t = new ChildThread();
        t.start();
        System.out.println("Before interrupting");
        t.interrupt();
        System.out.println("After interrupting");
    }
}

Output

Before interrupting
Child Thread Before Sleeping
After interrupting
Child Thread Interrupted

 

Leave a reply