Java:wait() 是否从同步块中释放锁 [英] Java : Does wait() release lock from synchronized block

查看:94
本文介绍了Java:wait() 是否从同步块中释放锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的印象是 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"

请澄清我有点困惑.

http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html

推荐答案

在同步方法中调用wait是获取内在锁的简单方法"

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

这句话是错误的,是文档中的错误.

线程在进入同步方法时获取内在锁.同步方法中的线程被设置为锁的所有者并处于RUNNABLE 状态.任何试图进入锁定方法的线程都会成为 BLOCKED.

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.

当线程调用 wait 时,它会释放当前对象锁(它保留来自其他对象的所有锁),然后进入 WAITING 状态.

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

当其他线程在同一个对象上调用 notify 或 notifyAll 时,第一个线程将状态从 WAITING 更改为 BLOCKED,通知线程不会自动重新获取锁或变为 RUNNABLE,实际上它必须与所有其他阻塞线程争夺锁.

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 和 BLOCKED 状态都阻止线程运行,但它们非常不同.

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

WAITING 线程必须通过来自其他线程的通知显式转换为 BLOCKED 线程.

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

WAITING 永远不会直接进入 RUNNABLE.

WAITING never goes directly to RUNNABLE.

当 RUNNABLE 线程释放锁(通过离开监视器或等待)时,一个 BLOCKED 线程会自动取而代之.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆