Java 中的 wait() 和 notify() 如何工作?
How does wait() and notify() work in Java?
我是 OS/multithreading 的新手,我想知道 wait()
和 notify()
如何协同工作。我刚看到这个:Producer Consumer Solution in Java
我有点困惑。假设我在 PC.consume()
方法中调用了 wait()
。当我到达 PC.produce()
中写着 notify()
的行时,PC.consume()
中的等待如何知道那是被通知的人?可能还有其他地方可以被通知,那么它如何确切地知道要通知哪个地方?
谢谢!
wait 和 notify 在同一个对象上被调用,一个被用作锁(在这个例子中是局部变量 pc 引用的对象)。 javadoc 中使用的术语(此处是通知方法的 api 文档的开头)是“monitor”:
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.
OS 有一个线程调度程序,它正在做出 javadoc 中描述的任意决定,它决定线程何时进行上下文切换或谁收到通知等事情。
因此,当消耗中的线程等待时,它会进入休眠状态。然后最终一些其他线程(在这个例子中只有两个线程获取 pc 上的锁)在同一个对象上调用通知第一个线程调用等待,调度程序选择要通知的线程(必须是这里的第一个线程因为没有其他东西在等待),并且被通知的线程醒来并检查是否有任何东西可以使用,这样它就可以知道是否继续。
我是 OS/multithreading 的新手,我想知道 wait()
和 notify()
如何协同工作。我刚看到这个:Producer Consumer Solution in Java
我有点困惑。假设我在 PC.consume()
方法中调用了 wait()
。当我到达 PC.produce()
中写着 notify()
的行时,PC.consume()
中的等待如何知道那是被通知的人?可能还有其他地方可以被通知,那么它如何确切地知道要通知哪个地方?
谢谢!
wait 和 notify 在同一个对象上被调用,一个被用作锁(在这个例子中是局部变量 pc 引用的对象)。 javadoc 中使用的术语(此处是通知方法的 api 文档的开头)是“monitor”:
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.
OS 有一个线程调度程序,它正在做出 javadoc 中描述的任意决定,它决定线程何时进行上下文切换或谁收到通知等事情。
因此,当消耗中的线程等待时,它会进入休眠状态。然后最终一些其他线程(在这个例子中只有两个线程获取 pc 上的锁)在同一个对象上调用通知第一个线程调用等待,调度程序选择要通知的线程(必须是这里的第一个线程因为没有其他东西在等待),并且被通知的线程醒来并检查是否有任何东西可以使用,这样它就可以知道是否继续。