java wait 释放锁,Java:wait()从同步块释放锁

I was under the impression that wait() releases all locks but I found this post which says

"Invoking wait inside a synchronized method is a simple way to acquire the intrinsic lock"

Please clarify I'm a bit confused.

解决方案

"Invoking wait inside a synchronized method is a simple way to acquire the intrinsic lock"

This sentence is false, it is an error in documentation.

Thread acquires the intrinsic lock when it enters a synchronized method.

Thread inside the synchronized method is set as the owner of the lock and is in RUNNABLE state.

Any thread that attempts to enter the locked method becomes BLOCKED.

When thread calls wait it releases the current object lock (it keeps all locks from other objects) and than goes to WAITING state.

When some other thread calls notify or notifyAll on that same object the first thread changes state from WAITING to BLOCKED,

Notified thread does NOT automatically reacquire the lock or become RUNNABLE, in fact it must fight for the lock with all other blocked threads.

WAITING and BLOCKED states both prevent thread from running, but they are very different.

WAITING threads must be explicitly transformed to BLOCKED threads by a notify from some other thread.

WAITING never goes directly to RUNNABLE.

When RUNNABLE thread releases the lock (by leaving monitor or by waiting) one of BLOCKED threads automatically takes its place.

So to summarize, thread acquires the lock when it enters synchronized method or when it reenters the synchronized method after the wait.

public synchronized guardedJoy() {

// must get lock before entering here

while(!joy) {

try {

wait(); // releases lock here

// must regain the lock to reentering here

} catch (InterruptedException e) {}

}

System.out.println("Joy and efficiency have been achieved!");

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值