Consider a scenario: Thread A is waiting in wait() inside a synchronized block. Thread B calls notify(). What is the state of Thread A?
AThread A transitions to runnable state after acquiring the lock
BThread A immediately starts executing
CThread A remains blocked permanently
DThread A is terminated
Correct Answer:
A. Thread A transitions to runnable state after acquiring the lock
EXPLANATION
After notify(), the waiting thread transitions to runnable state, but it must still acquire the lock before resuming execution within the synchronized block.
What is the primary difference between Semaphore and Mutex?
ASemaphore allows multiple threads to access a resource, Mutex allows only one
BMutex allows multiple threads, Semaphore allows only one
CThey are identical
DSemaphore is used for I/O operations only
Correct Answer:
A. Semaphore allows multiple threads to access a resource, Mutex allows only one
EXPLANATION
A Semaphore maintains a count allowing multiple threads (based on permit count) to access a resource. A Mutex (binary semaphore with count=1) allows only one thread.
ATo release the lock and make the thread wait until another thread calls notify()
BTo pause the thread execution indefinitely
CTo create a new thread
DTo check if a thread is alive
Correct Answer:
A. To release the lock and make the thread wait until another thread calls notify()
EXPLANATION
wait() releases the monitor lock and causes the thread to wait until notify() or notifyAll() is called by another thread, enabling inter-thread communication.
What is the output of the following code?
volatile int counter = 0;
counter++; // in multiple threads
Which issue may occur?
ARace condition because counter++ is not atomic
BNo issue, volatile ensures thread safety
CDeadlock will occur
DOutOfMemoryError
Correct Answer:
A. Race condition because counter++ is not atomic
EXPLANATION
volatile only ensures visibility, not atomicity. counter++ is actually three operations (read, increment, write), so even with volatile, race conditions can occur.