Java – how do I call the wait () and notify () methods on non threaded objects?

How do I call the wait () and notify () methods on an object that is not a thread? That really doesn't make sense, does it?

Of course, it must make sense because these two methods can be used for all Java objects Can anyone provide an explanation? I can't understand how to use wait () and notify () to understand the communication between threads

Solution

Locking is about protecting shared data

Lock on protected data structures Threads are things that access data structures Lock on the data structure object to prevent threads from accessing the data structure in an unsafe way

Any object can be used as an internal lock (meaning used with synchronized) In this way, you can protect access to any object by adding the synchronized modifier to the method of accessing shared data

Call the wait and notify methods on the object used as the lock A lock is a shared communication point:

>When a thread with a lock calls notifyAll, other threads waiting for the same lock will be notified When a thread with a lock calls notify, one of the threads waiting for the same lock will be notified. > When a thread with a lock call waits for it, the thread releases the lock and enters a sleep state until a) it receives a notification, or b) it just wakes up arbitrarily ("false Wake"); For one of these two reasons, the waiting thread still stays in the call waiting until it wakes up, and then the thread must regain the lock to exit the waiting method

See Oracle tutorial on guarded blocks. The drop class is a shared data structure that is being accessed by threads using producer and consumer runnables Locking the drop object controls how the thread accesses the data of the drop object

Threads are used as locks in JVM implementation. It is recommended that application developers avoid using threads as locks For example, documentation for thread Join said:

Java 5 introduces the implementation of Java util. concurrent. locks. Explicit lock for lock These are more flexible than implicit locks; There are methods like wait and notify, but they are conditional, not locked Having multiple conditions makes it possible to target only those threads waiting for a particular type of notification

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
分享
二维码
< <上一篇
下一篇>>