加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么我们需要在同一个对象上同步以使notify()工作

发布时间:2020-12-14 16:28:15 所属栏目:Java 来源:网络整理
导读:我收到了 java.lang.IllegalMonitorStateException.我提到了 this问题,它解决了我的问题.第一个答案是 To be able to call notify() you need to synchronize on the same object.synchronized (someObject) { someObject.wait();}/* different thread / obj
我收到了 java.lang.IllegalMonitorStateException.我提到了 this问题,它解决了我的问题.第一个答案是
To be able to call notify() you need to synchronize on the same object.

synchronized (someObject) {
    someObject.wait();
}

/* different thread / object */
synchronized (someObject) {
    someObject.notify();
}

我的问题是为什么我们需要在同一个对象广告上同步它的工作原理?

据我所知,据我所知

synchronized (someObject) {
    someObject.wait();
}

我们得到对象someObject的锁,然后我们调用wait().现在,另一个线程怎么能锁定同一个对象来调用notify()呢?我错过了什么?

解决方法

为什么通知也需要锁?

想象一下这种情况:

synchronized(x){
        while(x.count < 4) {
          x.wait();
          //...
        }
}

想象一下,现在在其他地方通知,没有任何锁定:

//...
println(x.count); // print 3
x.count++;
if(count == 4) 
  x.notify()
//...

乍一看,整个声音始终按预期工作.
但是,想象一下这种竞争条件:

//Thread1 enters here
synchronized(x){
     while(x.count < 4) {
         //condition is judged true and thread1 is about to wait 
         //..but..ohh!! Thread2 is prioritized just now !
         //Thread2,acting on notify block side,notices that with its current count incrementation,//count increases to 4 and therefore a notify is sent.... 
         //but...but x is expected to wait now !!! for nothing maybe indefinitely !
       x.wait();
       //maybe block here indefinitely waiting for a notify that already occurred!
     }
}

如果我们有办法告诉这个通知方:

线程1:“哼哼……通知,你很可爱,但我刚刚开始评估我的情况(x.count< 4)为真,所以请...刚才发送你的预期通知不要太傻了(在我把我的状态等待之前),否则,等待已经过去的事情我会是荒谬的“ 线程2:“好的好吧……为了保持一致,我会锁定我的逻辑,这样我就会在你的等待通话发出我们的共享锁之后发送通知,因此你会收到这个通知,允许你退出等待状态 ;)” 因此,始终在通知端对等待保持的同一对象进行锁定,以避免这种情况并使关系始终保持一致. =>导致通知的逻辑和导致等待的逻辑永远不应重叠.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读