1

I am trying to interrupt a normally running thread (which is not in sleep() or wait() state) .

while going through in net i got to know interrupting a normally running thread will just set the flag true and continue the process.

Code snippet is

one.java

......
......
actionperformedmethod {

if (actionCmd.equals("cancel")) {
    try {
        r1.stop();  // to two.java
    } catch (InterruptedException ex) {
        ....
        ....
    }
}
}

in two.java

.....
.....
stop method() throws InterruptedException{
        if(!(t.isInterrupted())){
            t.interrupt();
            throw new InterruptedException();
        }
}

from two.java when i throw InterruptedException i can able to get the exception block at one.java , but how do i stop the thread after that because even after that thread seems to continue the normal process.

Am new to thread concepts please help..

Ashot Karakhanyan
  • 2,804
  • 3
  • 23
  • 28
madhu
  • 37
  • 1
  • 10

3 Answers3

6

The interrupt() method is co-operative rather than pre-emptive - the background task needs to actively check Thread.interrupted() at suitable intervals, and take action to shut itself down cleanly.

public void run() {
  openSomeResources();
  try {
    while(notFinished) {
      if(Thread.interrupted()) return;
      doSomeStuff();
    }
  } finally {
    closeTheResources();
  }
}

In this example if the thread is interrupted in the middle of doSomeStuff() then it will complete the current "iteration" before responding to the interruption. Getting the correct balance between responding promptly to an interrupt on the one hand, and responding only at a safe point in the execution on the other hand, is something that is inherently specific to the particular task - there is no one-size-fits-all answer.

Note however that any blocking method that throws an InterruptedException will reset the interrupt flag when this exception is thrown. Therefore in order for this sort of checking to work you must re-interrupt yourself whenever you receive an InterruptedException

try {
  Thread.sleep(3000);
} catch(InterruptedException e) {
  // we were interrupted - set the flag so the next interrupted() check will
  // work correctly.
  Thread.currentThread().interrupt();
}
Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
2

Interrupt will not stop the thread. it just sets the flag to true to signal the thread to stop the execution soon.

to stop the execution add global variable as

private volatile boolean exit = false;

and you add one method in your 2nd class

public void requestExit(){
  exit = true;
 }

inside run () of your thread do something like this

 if (exit == true){
    return;
   }

whenever you want to call just call this method requestExit() from your main() or wherever you want to stop

this is the best way to stop the thread.. using stop() on thread is dangerous as it does not clear any resources and its not advisable to use even by oracle hence deprecated.

let me know for any issues

Karibasappa G C
  • 2,686
  • 1
  • 18
  • 27
  • Thanks for the reply .. Inside run method i have some 6 methods, My doubt is where should i put the check of (exit == true) ?? should it be there before each method call inside run()? – madhu Apr 23 '14 at 09:23
  • yes it is better to keep at the begining but again if you want some methods to execute mandatory then put this condition after those method calls.. – Karibasappa G C Apr 23 '14 at 09:25
  • Yes at the beginning of run method i have this exit == true check my quest is,if program is executing third method inside run() and now i interrupt the thread, i can know it only after the third method completes its execution?(because i will be having (exit == true) check before fourth method) – madhu Apr 23 '14 at 09:34
  • yes thats why i told you to put at the begining...and if you want it to stop at every point then put this condition before each method call and so that whenever you call , it will stop...but if your method is executing in between you can stop only if you put the same stop logic inside your method...it depends on your need where you want to stop – Karibasappa G C Apr 23 '14 at 09:40
0

Threads are only running whilst their run() method is on the stack so usually people put a while(true) inside the run method, all you need to do in you thread to stop it is to return somewhere in the run method or break the loop then as soon as the run() method is no longer running the thread has been stopped.

Basim Khajwal
  • 946
  • 6
  • 6
  • If the execution in run method is in mid-way , how could i use a return or break loop based on interrupt flag?? – madhu Apr 23 '14 at 09:18