java - wait()和notify()多线程中哪个线程持有锁

标签 java multithreading

我在下面的代码中对多线程感到困惑......

public class ThreadTest implements Runnable {
        private int num;
        private static SecondThread obj = new SecondThread();


        public void run() {
            synchronized (obj) { //which thread holding lock here 
                try {

                    obj.wait();   

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }   
            }   
        }   
    }
  1. 调用同步方法时哪个线程是所有者。
  2. 哪个线程持有锁 ThreadTest 或 SecondThread
  3. 这里释放锁是什么意思 obj.wait();方法 ?一旦锁被释放,同一个对象是否可以进入同步块(synchronized block)并访问代码,直到前一个线程得到通知?

最佳答案

From the Javadocs (加粗我的):

public final void wait(long timeout)
            throws InterruptedException

...

This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. Thread T becomes disabled for thread scheduling purposes and lies dormant until one of four things happens:

  • Some other thread invokes the notify method for this object and thread T happens to be arbitrarily chosen as the thread to be awakened.
  • Some other thread invokes the notifyAll method for this object.
  • Some other thread interrupts thread T.
  • The specified amount of real time has elapsed, more or less. If timeout is zero, however, then real time is not taken into consideration and the thread simply waits until notified.

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.

因此,在您的示例中:

  1. 线程进入您的 run() 方法,然后等待获取 obj 上的锁。
  2. 一旦获得该锁,就会进入 obj.wait() 并释放 obj() 上的锁。
  3. 当它醒来时(由于上述四个原因之一),它会等待获取 obj 的锁,然后再从 obj.wait() 返回。<

“哪个线程持有锁?”的答案完全取决于您检查对象的时间。如果所有线程都阻塞在 obj.wait() 中等待唤醒,则没有线程持有锁。

关于java - wait()和notify()多线程中哪个线程持有锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47692933/

相关文章:

java - 使用 XSLT 和 XSL-FO/FOP 将 XML 文件转换为 PDF

database - 我可以将多线程与 Perl 的 DBI 和 Oracle 一起使用吗?

c++ - Boost asio 用于多个异步网络客户端操作

c++ - 使用 boost::thread 将 c++ 对象从一个线程传递到另一个线程的正确方法是什么?

c++ - 客户端断开连接后处理服务器应用程序中的线程

java - 如何将已解析的依赖项复制到新位置,根据依赖项详细信息动态创建目录

java - 通过 RMI : any sense? 访问 session 范围的 bean

java - Jung Graph 未显示在 Jpanel 上

java - 在 Elasticsearch 中搜索列数据的最后四位

javascript - Web Worker 开销指标