Reputation: 99
This should be a simple take for any Java Master. Me being a newbie just wanted to confirm one thing.
I have a class implementing Runnable and like many such classes its run() method has an infinite loop. I want to do some task and then sleep for a min and come back again.
What happens if an Interrupted Exception is encountered while a thread is sleeping?
What I think would happen is the thread being suspended and now the infinite loop is of no help to keep the thread runnning. I'd like to confirm if my understanding is correct or not.
If this is what happens, What would be a possible solution to start up the thread up again.?
Upvotes: 3
Views: 581
Reputation: 96385
InterruptedExceptions don't just happen. Some exceptions, like IOExceptions, happen unpredictably due to inherent flakiness of the medium, but that is not the case for interruptions.
Interruption is a deliberate signal to a thread, usually sent by the application while it is shutting down, that it should finish up what it's doing and stop running. If the thread getting interrupted happens to be waiting or sleeping at the time, then the thread gets woken up and an InterruptedException gets thrown from the wait or sleep method.
Useful libraries like java.util.concurrent and guava use interrupts for thread cancellation. If you try to use them for something else then you can't use those libraries.
Upvotes: 0
Reputation: 23265
The thread will not be suspended.
If you catch the InterruptedException
, execution will continue in your exception handler.
If you do not catch the InterruptedException
, the thread will terminate.
Upvotes: 0
Reputation: 7523
Your understanding is mostly correct - When your thread is sleeping , if it gets interrupted , this will cause an InterruptedException
to be thrown - your code in run()
will have to catch it and do what it wants to do. The thread itself will not be suspended - because active execution continues on this thread.
You may want to continue the execution of the thread after you handle the InterruptedException
in your catch block.
Upvotes: 2
Reputation: 887305
Wrong.
An InterruptedException
would just terminate the sleep()
call and throw an exception.
As long as you handle the exception appropriately, your thread will continue running.
Upvotes: 6