2

I want to resume the work of interrupted thread,please let me know some possible solutions for the same.

class RunnableDemo implements Runnable 
{

   public void run() 
   {
    while(thread.isInterrupted())
        {
        try{}
                catch(Exception e){ //exception caught}
        }

   }

}

If exception is caught, thread is interrupted, but even though exception is caught, i want thread to continue its work, so please suggest me some way to overcome this issue.

Thanks in advance

astack
  • 3,837
  • 7
  • 22
  • 21
  • 1
    This will continue when exception is caught `while(true) { try { doSomething(); } catch(Exception e) {} }` – anonymous Apr 08 '14 at 12:55

5 Answers5

8

Thread interruption is something you choose to obey when writing a thread. So if you don't want your thread to be interrupted, don't check the interrupted status and continue regardless.

The only time you'll need try/catch statements (with respect to thread interruption) is when calling blocking methods that throw InterruptedException. Then you'll need to avoid letting that exception stop your thread's work.

Of course... you should give some thought about whether this is a suitable way to behave. Thread interruption is a helpful thing and choosing not to adhere to it can be annoying to users of your code.

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
2

I have written a reusable code for getting this feature where thread can be pause and resume. Please find the code below. Your can extend PausableTask and override task() method:

public abstract class PausableTask implements  Runnable{

    private ExecutorService executor = Executors.newSingleThreadExecutor();
    private Future<?> publisher;
    protected volatile int counter;
    private void someJob() {
        System.out.println("Job Done :- " + counter);

    }

    abstract void task();

    @Override
    public void run() {
        while(!Thread.currentThread().interrupted()){
            task();
        }
    }

    public void start(){
        publisher = executor.submit(this);
    }

    public void pause() {
        publisher.cancel(true);
    }

    public void resume() {
        start();
    }

    public void stop() {
        executor.shutdownNow();
    }
}

Hope this helps. For further details check this link or give me shout in comment section. http://handling-thread.blogspot.co.uk/2012/05/pause-and-resume-thread.html

Mak
  • 596
  • 5
  • 10
  • I'm fairly new to Java, and completely unfamiliar with Future, but I think this looks like exactly what I'm trying to do. Could you please explain the difference between it and using myThread.join() and .start()? – donutguy640 Oct 03 '17 at 14:57
1

A thread get's interrupted only if someone called the interrupt() method of that thread and not because some other random exception was thrown while running your thread as you are thinking.

When the thread's interrupted() method is called, InterruptedException will be thrown in the thread if the thread is in the middle of a blocking operation (eg. IO read).

When the InterruptedException is thrown you should know that the interrupted status is cleared, so the next time you call isInterrupted() in your thread will give you false (even though you just cauth the InterruptedException)

Have this in mind while coding your threads. And if you don't understand what I am talking about stop coding multithreading and go read some books about concurrency in java.

David Hofmann
  • 5,683
  • 12
  • 50
  • 78
  • "in the middle of a blocking operation (eg. IO read)" - Sadly, this is not correct. Generally, *blocking* operations, and especially (most) IO operations, are *not* interruptible. – JimmyB Apr 08 '14 at 13:43
  • prove it. http://stackoverflow.com/a/4426050/39998 http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html#interrupt%28%29 – David Hofmann Apr 08 '14 at 14:24
  • 1
    Yes, there *are* interruptible IO operations in the *New IO (NIO)* package, like those on Selectors and *interruptible* Channels. Java's standard IO (`Stream`-based), however, is not interruptible, neither are non-channel operations on network `Socket`s, like `connect()`, for instance. Code blocked on entering `synchronized` blocks is not interruptible either. My point is: *Most* "blocking operations" in the IO domain are not interruptible, except for those which are specifically designed to be and which usually need to be chosen explicitly by the programmer. – JimmyB Apr 08 '14 at 14:55
1

One caveat: If your thread handles an InterruptedException while in a call to a third-party library, then you won't necessarily know how the library reacted to it (i.e., did it leave the library objects in a state when it makes sense for your program to continue using them?)

Some developers (including some library developers) mistakenly assume that an interrupt means, "shut down the program," and all they worry about is closing files, etc.; and not so much about whether the library can continue to be used.

Try it and see, but if you're writing code to control a spacecraft or a nuclear reactor or something, then you may want to do a little extra work to really find out what the library does.

Solomon Slow
  • 25,130
  • 5
  • 37
  • 57
1

As others already stated, usually interruption is the proper way to cancel a task. If you really need to implement a non-cancellable task, at least make sure to restore the interrupted-state of the thread when you're done with your non-interruptible work:

public void run() {
    boolean interrupted = false;
    try {
        while (true) {
            try {
                callInterruptibleMethod();
            } catch (InterruptedException ex) {
                interrupted = true;
                // fall through and retry
            }
        }
    } finally {
        if (interrupted) {
            // restore interruption state
            Thread.currentThread().interrupt();
        }
    }
}

(From book: Java Concurrency in Practice)

isnot2bad
  • 24,105
  • 2
  • 29
  • 50