Implementation of thread waiting and notification in Java

Implementation of thread waiting and notification in Java

preface:

The key points to remember about waiting / notification are:

The wait(), notify(), notifyall() methods must be called from within the synchronization environment. A thread cannot call a method that waits or notifies on an object unless it has a lock on that object.

Wait(), notify(), and notifyall() are object instance methods. Just as each object has a lock, each object can have a list of threads waiting for a signal (notification) from the object. The thread obtains the waiting list by executing the wait () method on the object. From then on, it will not execute any other instructions until the notify () method of the object is called. If multiple threads are waiting on the same object, only one thread (in which order is not guaranteed) will be selected to continue. If there is no thread waiting, no special action will be taken.

Example code:

Synchronization can be at the class level, synchronized (a.class), or synchronized (this) at the object level. It can be a static synchronization method, static synchronized. The static synchronization method is at the class level, and the non static synchronization method is at the class object level. A class object has only one lock, and the wait operation can be performed on it only after obtaining the lock, Release the lock after.

Further example codes are as follows:

If you have any questions, please leave a message or go to the community of this site for exchange and discussion. Thank you for reading. I hope it can help you. Thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>