简体   繁体   English

Android / java:synchronized对象并通知

[英]Android / java: synchronized object wait and notify

I get confused on the synchronized method. 我对同步方法感到困惑。 Look at this code below: 请看下面的代码:

public void waitOne() throws InterruptedException
{
    synchronized (monitor)
    {
        while (!signaled)
        {
           monitor.wait();
        }
    }
}

public void set()
{
    synchronized (monitor)
    {
        signaled = true;
        monitor.notifyAll();
    }
}

Now, from what I understand, synchronized means only 1 thread can access the code inside. 现在,根据我的理解,synchronized意味着只有1个线程可以访问里面的代码。 If waitOne() is called by main thread and set() is called by child thread , then (from what I understand) it will create deadlock . 如果主线程调用waitOne()并且子线程调用set() ,那么(根据我的理解)它将创建死锁

This is because main thread never exit synchronized (monitor) because of while (!signaled) { monitor.wait(); } 这是因为主线程永远不会退出同步(监视器)因为while (!signaled) { monitor.wait(); } while (!signaled) { monitor.wait(); } and therefore calling set() from child thread will never able to get into synchronized (monitor) ? while (!signaled) { monitor.wait(); }因此调用从子线程组()将永远无法进入同步(显示器)?

Am I right? 我对吗? Or did I miss something? 还是我错过了什么? The full code is in here: What is java's equivalent of ManualResetEvent? 完整的代码在这里: 什么是Java相当于ManualResetEvent?

Thanks 谢谢

When you call wait on an object that you use to synchronize on, it will release the monitor, allowing​ another thread to obtain it. 当您在用于同步的对象上调用wait时,它将释放监视器,允许另一个线程获取它。 This code will not deadlock. 这段代码不会死锁。

Have a look at documentation of wait() method. 看看wait()方法的文档。

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. 导致当前线程等待,直到另一个线程为此对象调用notify()方法或notifyAll()方法。 In other words, this method behaves exactly as if it simply performs the call wait(0). 换句话说,此方法的行为就像它只是执行调用wait(0)一样。

The current thread must own this object's monitor. 当前线程必须拥有此对象的监视器。 The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. 线程释放此监视器的所有权并等待,直到另一个线程通过调用notify方法或notifyAll方法通知等待此对象监视器的线程唤醒。 The thread then waits until it can re-obtain ownership of the monitor and resumes execution. 然后线程等待,直到它可以重新获得监视器的所有权并继续执行。

The key point is the thread releases ownership of monitor and hence you won't get deadlock. 关键点是线程释放了监视器的所有权,因此你不会遇到死锁。 Child thread can set the value of signaled and can notify main thread. 子线程可以设置signaled的值,并可以通知主线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM