# java里Object.notify()方法的作用

{% embed url="<https://v.douyin.com/r6GVP5h/>" %}

{% embed url="<https://www.bilibili.com/video/BV15q4y1873E/>" %}

之前我在学习 object 里面

notify方法的时候

网上大部分的教程都是在main方法里

写了一些代码来讲解

然后呢我就觉得这种方法理解起来哈

不是那么容易

所以呢今天我用三个 Controller（HTTP请求）

给大家分享一下他们的使用方法

那说到 notify 我们就要说 wait

这两个方法都是在

synchronized 的里边使用的

也就说：他们都跟锁有关系

第一个 Controller 呢就是很简单

做了一把锁

然后呢我们在这做了一个 wait

就意味着所有的请求进来之后

都会被卡在这个地方

第二个

也是更简单哈

就在 synchronized 的里面做了一个 notify

第三个一样 notifyAll 我们来试一下哈

首先呢先来一个请求

produce的（001）

大家看：001进入

什么意思呢

也就说现在001

这个 id 的线程进来之后是卡在这了

（因为）他没有被唤醒

然后呢我们再来一个窗口

002

大家看：002进来了！这说明什么呢

说明001卡在这的同时他释放了锁

否则002是进不来的

对吧！我们再来一个003

大家看003也进来了

也就是说现在

有三个线程是卡在这个地方

并且他们都释放了这把锁

好那我们再来一个 notify 大家看啊 notify

在这里

因为他们都释放锁了 notify 肯定会进来

进来的话他就会执行这个 notify 方法

打开第一个有结果了

就说他会唤醒

第一个

第二个和第三个现在都还卡着呢

我们先再执行一下 notify

大家看！第二个也被唤醒

同时呢第二个也有响应了

同理第三个也是，我们再执行一下

第三个被唤醒

好 这就是notify()

然后 notifyAll() 呢

字面理解也很容易理解

他就直接全部唤醒

好我们再来试一下

001、002、003

好我们在执行下notifyAll()

大家看！3被唤醒、2被唤醒、1被唤醒

这里边顺序就很有意思

notifyAll的时候他是这种后进后出的顺序

那一个一个 notify 的时候呢

就是先进先出的顺序


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sunzsh.gitbook.io/xiaoshan.bug/java-li-object.notify-fang-fa-de-zuo-yong.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
