3

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.?

4

4 に答える 4

6

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.

于 2012-09-14T19:20:25.430 に答える
2

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.

于 2012-09-14T19:22:48.823 に答える
0

スレッドは中断されません。

をキャッチするInterruptedExceptionと、例外ハンドラで実行が続行されます。

をキャッチしないInterruptedExceptionと、スレッドは終了します。

于 2012-09-14T19:37:48.287 に答える
0

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.

于 2012-09-14T19:41:09.373 に答える