Sobes.tech
Junior — Middle

What are the main methods of the Object class used for working with threads and synchronization?

sobes.tech AI

Answer from AI

In Java, the Object class provides several methods that are frequently used when working with threads and synchronization:

  • wait() — causes the current thread to wait until another thread calls notify() or notifyAll() on the same object. It is used to organize waiting for a certain condition.

  • notify() — wakes up one thread that is waiting on this object.

  • notifyAll() — wakes up all threads waiting on this object.

These methods must be called within a synchronized block or method, otherwise an IllegalMonitorStateException will be thrown.

Example usage:

synchronized (sharedObject) {
    while (!condition) {
        sharedObject.wait();
    }
    // Actions after the condition is met
}

// In another thread
synchronized (sharedObject) {
    // Change state
    sharedObject.notify();
}