4

I got a question about interrupting threads in Java. Say I have a Runnable:

public MyRunnable implements Runnable {
    public void run() {
        operationOne();
        operationTwo();
        operationThree();
    }
}

I want to implement something like this:

Thread t = new Thread(new MyRunnable());
t.run();

... // something happens
    // we now want to stop Thread t

t.interrupt(); // MyRunnable receives an InterruptedException, right?

... // t is has now been terminated.

How can I implement this in Java? Specifically, how do I catch the InterruptedException in MyRunnable?

1
  • BTW, if you missed my answer below, line 2 of your 2nd block of code should be t.start(), not t.run(). Commented Dec 6, 2011 at 19:29

5 Answers 5

3

I recommend testing for Thread.isInterrupted(). Javadoc here. The idea here is that you are doing some work, most likely in a loop. On every iteration you should check if the interrupted flag is true and stop the work.

while(doingWork && !Thread.isInterrupted() {
  // do the work
}

Edit: To be clear, your thread won't receive an InterruptedException if the sub tasks are not blocking or worst, eat that exception. Checking for the flag is the right method but not everybody follows it.

Sign up to request clarification or add additional context in comments.

16 Comments

What if I need to check during a given operation?
@ryyst you will have to check during that given opertaions
You need to check for that condition inside each condition. If each of those conditions are short lived then no harm, but if each one is doing some work then you should check in operation also.
@JohnVint: Those operations are part of an API, so I can't change them.
I am not certain there is a way to do this. If operationOne() doesn't honor the interrupt flag then you have no choice to wait for each operation to complete and check your self. If it is something that is looking for disk IO or network then it should honor the interrupt flag. You can read more about this at stackoverflow.com/questions/671049/…
|
1

First, the 2nd line of your 2nd block of code should be t.start(), not t.run(). t.run() simply calls your run method in-line.

And yes, MyRunnable.run() must check periodically, while it is running, for Thread.currentThread().isInterrupted(). Since many things you might want to do in a Runnable involve InterruptedExceptions, my advice is to bite the bullet and live with them. Periodically call a utility function

public static void checkForInterrupt() throws InterruptedException {
   if (Thread.currentThread().isInterrupted())
      throw new InterruptedException();
}

EDIT added

Since I see a comment that the poster has no control over the individual operations, his MyRunnable.run() code should look like

public void run() {
  operation1();
  checkForInterrupt();
  operation2();
  checkForInterrupt();
  operation3();
}

Comments

1

I think the answers above will pretty much fit your problem. I just want to add something on InterruptedException

Javadoc says:

InterruptedException :Thrown when a thread is waiting, sleeping, or otherwise paused for a long time and another thread interrupts it using the interrupt method in class Thread.

This means InterruptedException won't be thrown while running

operationOne();
operationTwo();
operationThree();

unless you are either sleeping, waiting for a lock or paused somewhere in these three methods.

EDIT If the provided code can not be changed as suggested by the nice and useful answers around here then I am afraid you have no way of interrupting your thread. As apposed to other languages such as C# where a thread can be aborted by calling Thread.Abort() Java does not have that possibility. See this link to know more about the exact reasons.

1 Comment

It is possible that the author of those methods considered multi-threading and checks for isInterrupted() and/or throws an InterruptedException. Though that should have been documented!
0

an InterruptedThreadException is only thrown when the thread is being blocked (wait, sleep, etc.) . Otherwise, you'll have to check Thread.currentThread().isInterrupted().

Comments

-1

First of all, should be class in there

public class MyRunnable extends Thread {
    public void run() {
        if(!isInterrupted()){
            operationOne();
            operationTwo();
            operationThree();
        }
    }
}

Would this work better?

1 Comment

He doesn't need to extend Thread and he should also check for that flag in operationOne, two and three.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.