Search code examples
javamultithreadingrunnable

Non-passive waiting on a thread


Is it possible for a thread to do some operations before being Waited , what I want to do is that I want this thread to wait() another thread before being waited itself,

It's a distributed system with Clients, a Transaction Manager, and a Lock Manager which the last two reside on a middleware server. The Lock Manager may wait() a thread of Transaction Manager, I want this thread to be able to wait() Client thread before being waited itself.


Solution

  • You cannot "wait" another thread. If you call wait() on an object, all it does is sending the current thread to sleep until it is notified (by notify() or notifyAll()) or due to a so called spurious wake-up. I would recommend reading the "Lesson: Concurrency" from the Java Tutorials. Especially the part about guarded blocks should be of interest to you.

    So, if you want to tell some other thread that you are about to start waiting on an object, for example like this

    // We are somewhere, in some method ...
    synchronized(someObj) {
        someObj.wait();
    }
    

    you have to implement some kind of observer pattern, where other objects can be registered.