wait, sleep, notify,notifyall

xiaoxiao2023-03-19  54

wait() Causes the current thread to wait until either another thread invokes the notify()method or the notifyAll() method for this object, or a specified amount of time has elapsed. The current thread must own this object's monitor. 当线程调用wait()方法后,当前线程失去对象监视器。 此方法导致当前线程(称之为 T)将其自身放置在对象的等待集中,然后放弃此对象上的所有同步要求。出于线程调度目的,在发生以下四种情况之一前,线程 T 被禁用,且处于休眠状态: 其他某个线程调用此对象的 notify 方法,并且线程 T 碰巧被任选为被唤醒的线程。 其他某个线程调用此对象的 notifyAll 方法。 其他某个线程中断线程 T。 大约已经到达指定的实际时间。但是,如果 timeout 为零,则不考虑实际时间,在获得通知前该线程将一直等待。 然后,从对象的等待集中删除线程 T,并重新进行线程调度。然后,该线程以常规方式与其他线程竞争,以获得在该对象上同步的权利;一旦获得对该对象的控制权,该对象上的所有其同步声明都将被恢复到以前的状态,这就是调用 wait 方法时的情况。然后,线程 T 从 wait 方法的调用中返回。所以,从 wait 方法返回时,该对象和线程 T 的同步状态与调用 wait 方法时的情况完全相同。 在没有被通知、中断或超时的情况下,线程还可以唤醒一个所谓的虚假唤醒 (spurious wakeup)。虽然这种情况在实践中很少发生,但是应用程序必须通过以下方式防止其发生,即对应该导致该线程被提醒的条件进行测试,如果不满足该条件,则继续等待。 sleep() Causes the currently executing thread to sleep (temporarily ceaseexecution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors. 当线程调用sleep()方法后,当前线程不会失去对象监视器。 notify() Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods. 唤醒在此对象监视器上等待的单个线程。如果所有线程都在此对象上等待,则会选择唤醒其中一个线程。选择是任意性的,并在对实现做出决定时发生。线程通过调用其中一个 wait 方法,在对象的监视器上等待。 直到当前线程放弃此对象上的锁定,才能继续执行被唤醒的线程。被唤醒的线程将以常规方式与在该对象上主动同步的其他所有线程进行竞争;例如,唤醒的线程在作为锁定此对象的下一个线程方面没有可靠的特权或劣势。 此方法只应由作为此对象监视器的所有者的线程来调用。通过以下三种方法之一,线程可以成为此对象监视器的所有者: 通过执行此对象的同步实例方法。 通过执行在此对象上进行同步的 synchronized 语句的正文。 对于 Class 类型的对象,可以通过执行该类的同步静态方法。 一次只能有一个线程拥有对象的监视器。 notifyAll() Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods.The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object. The awakened threads will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example,the awakened threads enjoy no reliable privilege or disadvantage in being the next thread to lock this object.
转载请注明原文地址: https://www.6miu.com/read-4986696.html

最新回复(0)