interrupt() method interrupts a sleeping thread during its sleeping time.
- In the below example the main thread waits for the MyThread to complete using join method for 2 seconds.
- If the MyThread does not completes its execution in 2 seconds, then main thread interrupts MyThread and check if the Thread is still alive in loop.
class MyThread extends Thread {
public void run()
{
for (int i = 0; i < 500; i++) {
System.out.println("Child Thread executing : "+i);
try {
Thread.sleep(500);
}
catch (InterruptedException e) {
System.out.println("Interrupted Exception occured");
}
}
}
}
class Test {
public static void main(String[] args)
throws InterruptedException
{
MyThread thread = new MyThread();
thread.start();
while(thread.isAlive()) {
thread.join(2000);
thread.interrupt();
}
System.out.println("Main thread execution completes");
}
}
