2

Is there a reason these two and notifyAll() part of the Object class instead of the Thread class where other thread-related methods are?

breakline
  • 5,776
  • 8
  • 45
  • 84
  • 2
    I don't think its a duplicate of that question. That question answers what these are good for. I'm asking why it is in Object as why do they have to be in every object in Java? – breakline May 11 '15 at 21:23
  • 3
    in the beginning of Java, the creators were really proud of the fact that multi-threading is built in the language (as opposed to in a library, like C++), and they went a little crazy of promoting it:) – ZhongYu May 11 '15 at 21:24
  • lol, that makes sense (kinda) :) – breakline May 11 '15 at 21:25
  • 5
    It is explained in one of the answers. Please, do not readin only the most voted post. – Luiggi Mendoza May 11 '15 at 21:25
  • same reason for the `Vector` etc with `synchronized` everywhere – ZhongYu May 11 '15 at 21:26
  • 2
    He's right, [Nathan Hughes](http://stackoverflow.com/users/217324/nathan-hughes) answer explains this. – Rossiar May 11 '15 at 21:28
  • I think I know what the OP is missing. When you "notify" a thread, you're not specifying that thread directly, you're specifying the object whose wait() has been called within that thread. In this way, you can have any number of locks/monitors, one per object. –  May 11 '15 at 21:30
  • His answer makes sense but not fully. Yes any Object can be used as a lock, but wait() can only be used inside a synchronized block, meaning you already have a lock there, there is no reason for it to get implemented by every Object then. A static thread method could work as well. – breakline May 11 '15 at 21:30
  • 1
    @user2710256: no, a static thread method wouldn’t work as you can have *multiple* locks at a time. So you have to invoke `wait` on the right object (though waiting while holding another lock is not very recommended, it requires special care to avoid deadlocks). With explicit `Lock`s, it is even the case that you can `await` different `Condition`s associated with a single lock. Besides that, it would be very unnatural to have `synchronized` instance methods but not to call the associated `wait`/`notify` on the same instance but another class. – Holger May 12 '15 at 09:31
  • The key word (not well explained in the answers to the other question) is _monitor_ (http://en.wikipedia.org/wiki/Monitor_%28synchronization%29). The authors of Java wanted to make it possible for any object to be a monitor. – Solomon Slow May 12 '15 at 13:23

0 Answers0