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

前端 未结 4 1687
野性不改
野性不改 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:41

    These method's context is a lock associated with every object in Java so we can't move them to the Thread class. For example we might do something like this. Thread 1 adds an item to a list and notifies other threads about it. Thread 2 waits for a list update and does something with it:

    thread 1
    synchronized (lock) {
        list.add(item);
        lock.notifyAll();     
    }
    
    thred 2 
    synchronized (lock) {
        list.wait();
        ... do something with list
    }
    

    If these methods were moved to a thread, the thing we done here would be impossible.

提交回复
热议问题