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

前端 未结 9 998
耶瑟儿~
耶瑟儿~ 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:15

    You can stop your thread for time as you want using static Thread class method sleep().

    public class Main {
        //some code here
    
        //Thre thread will sleep for 5sec.
        Thread.sleep(5000);   
    }
    

    If you want to stop some objects you need to call this method's within syncronized blocks.

    public class Main {
    
    //some code
    
    public void waitObject(Object object) throws InterruptedException {
        synchronized(object) {
            object.wait();
        }
    }
    
    public void notifyObject(Object object) throws InterruptedException {
        synchronized(object) {
            object.notify();
        }
    }
    

    }

    P.S. I'm sory if I wrong understand your question (English is not my native)

提交回复
热议问题