为什么wait()必须要在放synchronized里面?

本文深入探讨了Java中对象wait()方法的使用原理。解释了为什么调用wait()必须在拥有对象锁的情况下进行,并且通常被放置在synchronized块内。此外,还介绍了线程如何通过释放锁并等待通知,以及如何通过notifyAll()方法唤醒等待的线程。

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

假如你要调用某个对象的wait()方法,一般都要放在synchronized声明里面,why? 下面是答案。

 

Suppose d is the object we're using to invoke wait. When a thread invokes d.wait, it must own the intrinsic lock for d — otherwise an error is thrown. Invoking wait inside a synchronized method is a simple way to acquire the intrinsic lock.

When wait is invoked, the thread releases the lock and suspends execution. At some future time, another thread will acquire the same lock and invoke Object.notifyAll, informing all threads waiting on that lock that something important has happened。

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值