Coordinating Java Threads - Quiz Explanation
The answers you selected are indicated below, along with text that explains the correct answers.
1.
When used with an instance method, the keyword
synchronized
ensures
Please select the best answer.
A.
That method can be invoked only by one thread at a time
B.
An exception is thrown if more than one thread tries to invoke the method
C.
There are no restrictions on invoking that method
The correct answer is A.
A synchronized method can be invoked only by one object at a time, so the correct answer is A.
2.
To lock only a portion of a method, you can write code like this
Please select the best answer.
A.
synchronized { /* code here */ }
B.
synchronized (void) { /* code here */ }
C.
synchronized (myObject) { /* code here */ }
The correct answer is C,
assuming
myObject
is an object reference. The
synchronized
keyword, if used to lock only a block of code, requires an object reference or a class name before the block of code.
3.
A thread is at a wait statement and is notified by another thread that has the lock on that object to proceed.
Under what conditions can the thread at the wait statement continue?
A.
Right away. It has been notified, and it can now go.
B.
The wait thread can continue once the notify thread has exited its synchronized block.
C.
The thread can continue once the notify thread has exited its synchronized block, and the wait thread has obtained the lock on that object.
The correct answer is C.
The thread can continue once the notify thread has exited its synchronized block, and the wait thread has obtained the lock on that object.