简体   繁体   English

通知仅限于同步构造

[英]Notify restricted to synchronized construct

I do realize that this topic has been discussed at many places. 我的确意识到这个话题已经在很多地方讨论过了。 But all of them talk about it's usage in multi-threaded environment. 但是所有人都谈论它在多线程环境中的用法。

In this following example, why is notify() supposed to be surrounded by synchronized ? 在下面的示例中,为什么notify()应该被synchronized包围? It goes in vain when the keyword is used, which it is supposed to do. 当使用该关键字时,它是徒劳的。 But why the exception, java.lang.IllegalMonitorStateException , when it is not used? 但是为什么不使用异常java.lang.IllegalMonitorStateException呢?

public class HelloWorld {
   public static void main(String[] args) {
      ABC c = new ABC();
      c.put(0);
   }
}
class ABC {
   public synchronized void put(int value) {    // why synchronized now!
      System.out.println("Put: " + value);
      notify();
   }
}

You supposed to use synchronized is because the lock is re-entrant , meaning that it can be acquired multiple times by the same thread. 您应该使用synchronized是因为锁是可re-entrant ,这意味着同一线程可以多次获取它。 In other words if your thread already holds the lock on an object it doesn't have to wait on itself. 换句话说,如果您的线程已经持有对象的锁,则不必等待它自己。

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

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