How can the wait() and notify() methods be called on Objects that are not threads?

前端 未结 9 982
耶瑟儿~
耶瑟儿~ 2020-11-29 19:00

How can the wait() and notify() methods be called on Objects that are not Threads? That doesn\'t really make sense, does it?

Surely, it mus

9条回答
  •  一生所求
    2020-11-29 19:28

    Think using a real life example, a washroom. When you want to use the washroom at your office, you have two options to make sure no one else will come to the washroom once you are using it.

    1. Lock the washroom door, so everyone else will know that it's used by someone else when they try to open the door
    2. Go to each person in the office, lock them to their chairs (or table, or whatever), go to washroom.

    Which option would you take?

    Yes, it's the same in the Javaland!.

    So in the above story,

    • Washroom = Object you want to lock (that only you need to use)
    • Your staff colleagues = other threads that you want to keep out

    So just like in real life, when you have some private business, you lock that object. And when you are done with that object, you let go of the lock!.

    (Yes yes!, this is a very simple description on what happens. Of course the real concept is slightly different from this, but this is a starting point)

提交回复
热议问题