File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread methods" Watch "Thread methods" New topic

Thread methods

adam Lui
Ranch Hand

Joined: Sep 03, 2007
Posts: 186
object: wait, notify, notifyAll
Thread: sleep, yield, join

which ones have to be in a try block?
arent they meant to be?
i have seen too many codes and i have been confused if they are meant to.
Kelvin Chenhao Lim
Ranch Hand

Joined: Oct 20, 2007
Posts: 513
Here's a simple trick for the exam: the only checked exception that any of these methods throw is InterruptedException. And, as the name implies, InterruptedException occurs if this thread is prematurely interrupted while it's supposed to be "inactive" in the background. Therefore, to figure out which of these six methods throw an unchecked exception, just ask yourself which of them will put the thread into an "inactive" state.

notify() and notifyAll() clearly do not, so they're out. yield() is a little trickier, but just remember that yield() is only a suggestion to the scheduler that it should temporarily go on to process another thread... but the scheduler can return to this thread at any time, so it's never premature to interrupt a yielded thread--thus yield() doesn't throw an InterruptedException either.

The other three methods (wait(), sleep(), and join()) all force the thread to become inactive until some condition is satisfied. Thus, if the thread is then interrupted before the condition is satisfied, this would be premature and will cause an InterruptedException.

And because InterruptedException is a checked exception, you must therefore always either handle or declare the exception in your calling method.
[ November 13, 2007: Message edited by: Kelvin Lim ]

SCJP 5.0
I agree. Here's the link:
subject: Thread methods
It's not a secret anymore!