Why wait ,notify and notifyAll Methods are in Object Class?

前端 未结 4 1689
野性不改
野性不改 2020-12-21 07:15

i know that wait() method always written in synchronized method/block and make lock on Object but i want to only know that what problem is arise at that time when this all m

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-21 07:27

    They are also in the Thread class. But a thread instance here is equally well suited as a synchronization object as any other object.

    In addition, there have already been voices that question this decision of sun, since now every object carries the burden to be able to be synchronized on, and IMHO they should have refactored this out to separate objects long ago.

    If I need to have something to synchronize on, I often do:

    private Object syncObject = new Object();
    

    Then I can do my

    synchronized(syncObject) 
    

    everywhere in the code and do not have to bother with anyone else accidentially synchronizing on this.

提交回复
热议问题