The other answers to this question all miss the key point that in Java, there is one mutex associated with every object. (I'm assuming you know what a mutex or "lock" is.) This is not the case in most programming languages which have the concept of "locks". For example, in Ruby, you have to explicitly create as many Mutex
objects as you need.
I think I know why the creators of Java made this choice (although, in my opinion, it was a mistake). The reason has to do with the inclusion of the synchronized
keyword. I believe that the creators of Java (naively) thought that by including synchronized
methods in the language, it would become easy for people to write correct multithreaded code -- just encapsulate all your shared state in objects, declare the methods that access that state as synchronized
, and you're done! But it didn't work out that way...
Anyways, since any class can have synchronized
methods, there needs to be one mutex for each object, which the synchronized
methods can lock and unlock.
wait
and notify
both rely on mutexes. Maybe you already understand why this is the case... if not I can add more explanation, but for now, let's just say that both methods need to work on a mutex. Each Java object has a mutex, so it makes sense that wait
and notify
can be called on any Java object. Which means that they need to be declared as methods of Object
.
Another option would have been to put static methods on Thread
or something, which would take any Object
as an argument. That would have been much less confusing to new Java programmers. But they didn't do it that way. It's much too late to change any of these decisions; too bad!