java.lang.Object-notify()方法介绍

本文详细介绍了Java中`notify()`和`notifyAll()`方法的使用及原理。这两个方法用于唤醒在对象监视器上等待的线程。`notify()`随机唤醒一个线程,而`notifyAll()`则唤醒所有线程。调用这两个方法的线程必须持有对象的监视器,即在同步代码块或方法中。唤醒的线程需要与其他线程竞争锁,才能继续执行。理解这些概念对于理解和编写多线程代码至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

notify()方法

源码介绍

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.

唤醒正在等待此对象监视器的单个线程。如果有几个线程正在等待这个对象,其中一个线程被选择唤醒。至于是唤醒哪一个线程,这种选择是随机的。随机唤醒一个正在等待此对象监视器的线程

The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object. The awakened thread will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened thread enjoys no reliable privilege or disadvantage in being the next thread to lock this object.  

在当前线程放弃对该对象的锁定之前,唤醒的线程将无法继续执行。唤醒的线程将以通常的方式与任何其他线程竞争,这些线程可能会积极地在这个对象上进行同步竞争;例如,唤醒的线程在成为下一个锁定此对象的线程时没有特权。唤醒的线程在其他线程没有放弃该对象的锁定之前,是无法执行的,唤醒的线程竞争对象的监控器的时候,是随机的,不一定是哪个线程会获取到

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways: 
•By executing a synchronized instance method of that object. 
•By executing the body of a synchronized statement that synchronizes on the object. 
•For objects of type Class, by executing a synchronized static method of that class. 

此方法只能由作为此对象监视器所有者的线程调用。只有获取对象的监视器后,才能调用notify方法。

线程通过以下三种方式之一成为对象监视器的所有者:

线程获取对象的监视器的三种方式:

•通过执行该对象的同步实例方法。调用该对象的同步方法。

•通过执行在对象上同步的synchronized语句体。执行synchronized语句体(锁定该对象)

•对于类类型的对象,执行该类的同步静态方法。

Only one thread at a time can own an object's monitor.

某一时刻只能有一个线程拥有某个对象的监视器。

public final void notify()

在执行notify()方法后,当前线程不会马上释放该对象锁,要等到执行notify()方法的线程退出synchronized方法或synchronized代码块后,或者在synchronized方法或synchronized代码块中调用该对象的wait方法后,当前线程才会释放锁。

此时wait状态的线程会被唤醒,并和其他线程竞争获取该对象锁,获取对象锁后,继续执行synchronized代码块中wait()方法后面的代码。

notifyAll():

Wakes up all threads that are waiting on this object's monitor.

唤醒所有正在等待此对象监视器的线程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值