Sobes.tech
Junior — Middle

Millised on Object klassi peamised meetodid, mida kasutatakse voogude ja sünkroniseerimisega töötamisel?

sobes.tech AI

Vastus AI-lt

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. Used to organize waiting for a specific condition.

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

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

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

Example usage:

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

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