Junior — Middle
Are mechanisms like synchronized, wait, and notifyAll used in practice for thread management?
sobes.tech AI
Answer from AI
Yes, in Java programming practice, the mechanisms synchronized, wait, and notifyAll are used for thread management, especially when low-level synchronization and coordination between threads are needed.
- synchronized is used to ensure mutual exclusion when accessing shared resources.
- wait() causes the current thread to wait, releasing the monitor, until another thread calls notify() or notifyAll().
- notifyAll() wakes up all threads waiting on the object.
However, in modern applications, higher-level tools from the java.util.concurrent package (such as Lock, Semaphore, CountDownLatch) are more commonly used because they are more flexible and convenient.
Example of using synchronized, wait, and notifyAll:
class SharedResource {
private boolean ready = false;
public synchronized void waitForReady() throws InterruptedException {
while (!ready) {
wait();
}
// continue work
}
public synchronized void setReady() {
ready = true;
notifyAll();
}
}