Friday, September 20

Java concurrency interrupt method theory , wating thread and interruptException

             Java concurrency interrupt method theory ,  wating thread and interruptException


java Thread interrupt method

one important thing to know about this method  :

This method throws interruption exception only for waiting thread .

If thread is not in waiting status thread's interrupted status will be set to true but it won't stop it's execution there instead thread will continue running normally

For example

class MyThread extends Thread {


public void run(){

try{
Thread.currentThread().sleep(100);

for (int i=0;i<100 br="" i="">System.out.println(i);
}
}catch(InterruptedException exp){
    System.out.println(1);
exp.getMessage();
}
 }

}

public class Test{

public static void main(String args[]){

Thread t=new MyThread();

t.start();
t.interrupt();

}
}
In above example when t.interrupt() method is invoked Mythread thread is in sleeping i.e. waiting status . So it would be interrupted and for loop won't be executed but execution control flow will land up directly in catch block .








Now let's change this scenario a bit


class MyThread extends Thread {


public void run(){

try{
Thread.currentThread().sleep(101);

for (int i=0;i<100 br="" i="">System.out.println(i);
}
}catch(InterruptedException exp){
    System.out.println(1);
exp.getMessage();
}
 }

}

public class Test{

public static void main(String args[]){

Thread t=new MyThread();

t.start();
try {
    Thread.sleep(101);
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
t.interrupt();

}


Here after starting the thread , t.interrupt() is not invoked immediately but after waiting for 101 ms . So , here when t.interrupt() in invoked MyThread thread has already come out of sleeping status. So it won't be interrupted and for loop will be executed normally without any exception.


Thus interrupt() method will cause interruptException only when invoked thread is in waiting status .

 

What are the different way , a thread can go in waiting status is listed here


-->




No comments:

Post a Comment