在java中提供关于等待和睡眠的详细信息

这个问题在这里已经有了答案:

  • wait()和sleep()之间的差异33个答案

  • sleep():这是一个Thread类的静态方法。 它使当前线程进入“Not Runnable”状态达指定的时间。 在此期间,线程保持它获取的锁定(监视器)。

    wait():它是Object类的一个方法。 它使当前线程进入“Not Runnable”状态。 等待是在一个对象上调用的,而不是一个线程。 在调用wait()方法之前,对象应该是同步的,意味着对象应该在同步块内。 等待()的调用释放获取的锁。 例如:

    synchronized(LOCK) {   
        Thread.sleep(1000); // LOCK is held
    }
    
    synchronized(LOCK) {   
        LOCK.wait(); // LOCK is not held
    }
    

    让我们对以上几点进行分类:

    呼吁:

    wait(): Call on an object; current thread must synchronize on the lock object.
    sleep(): Call on a Thread; always currently executing thread.
    

    同步:

    wait(): when synchronized multiple threads access same Object one by one.
    sleep(): when synchronized multiple threads wait for sleep over of sleeping thread.
    

    保持锁定:

    wait(): release the lock for other objects to have chance to execute.
    sleep(): keep lock for at least t times if timeout specified or somebody interrupt.
    

    唤醒条件:

    wait(): until call notify(), notifyAll() from object
    sleep(): until at least time expire or call interrupt().
    

    用法:

    sleep(): for time-synchronization and;
    wait(): for multi-thread-synchronization.
    
    链接地址: http://www.djcxy.com/p/92141.html

    上一篇: Provide the details about wait and sleep in java

    下一篇: Get output of a running bash script with java