Java:wait()从同步块释放锁 [英] Java : Does wait() release lock from synchronized block
问题描述
我的印象是wait()释放所有锁,但我发现这个帖子说
在同步方法中调用wait是一个简单的方法来获取内部锁
请澄清我有点困惑。
http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html
在同步方法中调用wait是获取内部锁的简单方法
这个句子是假的,它是文档中的错误。
strong>一种同步方法。
synchronized方法中的线程设置为锁的所有者,并处于 RUNNABLE 状态。
尝试进入锁定方法的任何线程将变为 BLOCKED 。
线程调用等待时释放当前对象锁
当一些其他线程调用通知或通知同一对象上的第一个线程更改状态从WAITING到BLOCKED,
通知的线程不会自动重新获取锁或者变成RUNNABLE,实际上它必须为所有其他被阻止的线程争取锁。
WAITING和BLOCKED状态都阻止线程运行,但它们是非常不同的。
WAITING线程必须通过一个其他线程的通知显式转换为BLOCKED线程。
当RUNNABLE线程释放锁定时(通过离开监视器或通过等待)BLOCKED线程中的一个自动占据它的位置。
总而言之,当线程进入同步方法或重新输入同步方法。等待。
public synchronized guardedJoy(){
//在输入之前必须锁定
while(!joy){
try {
wait(); //释放锁
//必须重新获得锁,才能重新进入这里
} catch(InterruptedException e){}
}
System.out.println已经实现!
}
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.
http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html
"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!");
}
这篇关于Java:wait()从同步块释放锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!