How can the wait() and notify() methods be called on Objects that are not threads?

前端 未结 9 974
耶瑟儿~
耶瑟儿~ 2020-11-29 19:00

How can the wait() and notify() methods be called on Objects that are not Threads? That doesn\'t really make sense, does it?

Surely, it mus

9条回答
  •  自闭症患者
    2020-11-29 19:11

    You can use wait() and notify() to synchronize your logic. As an example

    synchronized (lock) {
        lock.wait(); // Will block until lock.notify() is called on another thread.
    }
    
    // Somewhere else...
    ...
    synchronized (lock) {
        lock.notify(); // Will wake up lock.wait()
    }
    

    with lock being the class member Object lock = new Object();

提交回复
热议问题