A
thread can interrupt a sleeping or waiting thread by using interrupt() method of thread class.
§ public void
interrupt()
Example –
public class
Interrupt extends Thread{
public void
run()
{
for(int i=0;i<5;i++)
{
System.out.println(getName()+" Run : "+i);
try{
Thread.sleep(2000);
}
catch(InterruptedException
e)
{
System.out.println("I am interrupted");
}
}
}
public static void
main(String[] args) {
Interrupt i1 = new
Interrupt();
i1.start();
i1.interrupt();
System.out.println("End of main thread");
}
}
Output –
End of main thread
Thread-0 Run : 0
I am interrupted
Thread-0 Run : 1
Thread-0 Run : 2
Thread-0 Run : 3
Thread-0 Run : 4
Note – In the above program,
main thread interrupts child thread by using thread object. Whenever we are
calling interrupt() method and if the target thread isn’t in sleeping or
waiting state, then there is no effect of interrupt() method call immediately. This
call waits until thread enters into sleeping or waiting state. Once the target
thread enters into sleeping or waiting state, then interrupt call will
interrupt that thread. If the target thread never enters into sleeping and
waiting state in its lifetime, then the interrupt call will wait.
Example –
public class
Interrupt extends Thread{
public void
run()
{
for(int i=0;i<5;i++)
{
System.out.println(getName()+" Run : "+i);
try{
Thread.sleep(100);
}
catch(InterruptedException
e)
{
System.out.println("I am interrupted");
}
}
}
public static void
main(String[] args) {
Interrupt i1 = new
Interrupt();
i1.start();
i1.interrupt();
for(int i=0;i<5;i++)
{
System.out.println("main "+i);
}
}
}
No comments:
Post a Comment