javamultithreadingsynchronizedsynchronized-block

Using 'this' versus another object as lock in synchronized block with wait and notify


I have two blocks of code, one waits for the other to notify it.

synchronized(this) {
    wait();
}

and

while(condition) {
    //do stuff
    synchronized(this) {
        notify();
    }
}

Weirdly enough that didn't wait for the notify while this did:

synchronized(objectLock) {
    objectLock.wait();
}

and

while(condition) {
    //do stuff
    synchronized(objectLock) {
        objectLock.notify();
    }
}

I'm very curious about the difference of both sets, and why the first one worked while the other didn't. Note that the two blocks reside in two different threads on two different methods (if that helps).

I hope someone could explain why this is so. I edited my question so it would be more detailed.


Solution

  • It didn't work because you synchronized on this which in two different threads pointed to two different Thread objects.

    Synchronization with wait() and notify() would only work properly when you synchronize on the same object for locking like the objectLock that you used later on.

    EDIT: If the two thread instances belonged to the same MyThread class then to achieve the effect that you thought you're code was having, you would have to acquire a lock on their class object itself:

    synchronized(MyThread.class)