有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java会立即调用等待的线程吗?

我正在编写一个Java代码,其中在满足特定条件后,在等待线程上调用notify,但等待线程不会立即开始运行。原因可能是什么


共 (1) 个答案

  1. # 1 楼答案

    wait(以及notify)需要使用同步监视器。如果调用notify的代码没有释放它,那么wait将继续“等待”直到释放监视器

    // wait thread
    synchronized (syncObject) {
       syncObject.wait(); // to proceed to next line, 
                          // this thread must wait until notify is called 
                          // and then take ownership over syncObject
       // next line
    }
    
    ...
    
    // notify thread
    synchronized (syncObject) {
       syncObject.wait();
       while (true) {}; // infinite loop, syncObject is never released, 
                        // wait thread will never gain ownership over syncObject 
                        // and will never wake up 
    }