java - wait() 如何在 Java 中取回锁

标签 java multithreading synchronization locking wait

提倡的范例是 wait() 应该在同步块(synchronized block)内的 while 循环内调用。

我的问题是 waiting() 线程如何取回锁?

// Thread 1
    synchronized (mon) {
     while (!condition) 
          mon.wait();

    // Do something
    }

//Thread 2
    synchronized (mon) {//set condition appropriately
            mon.notify();
    }

考虑线程 1 首先运行并开始等待条件。它释放锁,线程 2 获得锁设置条件并通知线程 1。现在线程 1 获得锁,检查条件并开始执行“做某事”。

我的问题是,当通知线程 1 它从 while 条件开始执行时,具有 Synchronized(mon) 的代码行再也不会执行,那么线程 1 如何获取锁?将锁返回给线程 1 的内部动力是什么?

最佳答案

当 Thread1 被通知线程必须在退出等待方法之前获取锁,请参阅 Object#wait 的 java 文档:

The thread T is then removed from the wait set for this object and re-enabled for thread scheduling. It then competes in the usual manner with other threads for the right to synchronize on the object; once it has gained control of the object, all its synchronization claims on the object are restored to the status quo ante - that is, to the situation as of the time that the wait method was invoked. Thread T then returns from the invocation of the wait method. Thus, on return from the wait method, the synchronization state of the object and of thread T is exactly as it was when the wait method was invoked.

关于java - wait() 如何在 Java 中取回锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16760513/

相关文章:

java - 在客户端上生成 RMI stub

c - 当线程释放它的资源

synchronization - CouchDB:从属数据库之间同步

javascript - 在 onbeforeunload 中等待 promise

java - Google App Engine java OutOfMemoryError when putAll on memcache

c# - 如何从java调用DLL?

java - PreferenceFragment 中的文件选择器对话框

python - Flask 线程共享值

java - 确定哪个线程获得了同步 key

java - 在数据访问层使用同步