In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
In this issue, the editor will bring you an example analysis of wait and notify and consumer producers. The article is rich in content and analyzed and described from a professional point of view. I hope you can get something after reading this article.
First of all, when calling the wait and notify/notifyAll of an Object, you must ensure that the calling code is synchronized with the Object, that is, you can only call the wait and notify/notifyAll methods of obj if the function is equivalent to synchronized (obj) {.}, otherwise an error will be reported:
Java.lang.IllegalMonitorStateException:current thread not owner
When wait is called, the thread automatically releases the object lock it owns and does not apply for the object lock. When the thread is awakened, it gains the right to acquire the object lock again.
So, notify is not much different from notifyAll, except that notify wakes up only one thread and allows it to acquire a lock. NotifyAll wakes up all threads waiting for this object and allows them to acquire an object lock. As long as it is code in a synchronied block, it is impossible to move without an object lock. In fact, waking up a thread is to re-allow the thread to acquire the object lock and run down.
NotifyAll, although notify is called once for each wait object, there is an order for this. Each object holds this chain of waiting objects, and the order in which it is called is the order of the chain. In fact, it is also a thread that starts each thread in the waiting object chain, which needs to be paid attention to in the specific application.
Wait (), notify (), notifyAll () do not belong to the Thread class, but belong to the Object basic class, that is, each object has the function of wait (), notify (), notifyAll (). Because all objects have locks, locks are the basis of every object, and of course, the method of operating locks is also the most basic.
Wait ():
Wait for the synchronization lock of the object, and you need to obtain the synchronization lock of the object before you can call this method, otherwise the compilation can pass, but the runtime will receive an exception: IllegalMonitorStateException.
Calling the wait () method of any object causes the thread to block, the thread can no longer execute, and the lock on the object is released.
Notify ():
Wake up the thread waiting for the object's synchronization lock (only one, if more than one is waiting). Note that when this method is called, it does not exactly wake up a waiting thread, but it is up to JVM to determine which thread to wake up, not by priority.
Calling the notify () method of any object causes one of the randomly selected threads blocked by the call to the object's wait () method to unblock (but not really executable until the lock is acquired).
NotifyAll ():
Wake up all waiting threads, and note that wait threads before notify have no effect on wait threads after notify.
In general, multithreads need to coordinate work: if the condition is not met, wait; when the condition is met, the thread waiting for the condition will be awakened. In Java, the implementation of this mechanism depends on wait/notify. The waiting mechanism is closely related to the locking mechanism.
For example:
Synchronized (obj) {
While (! condition) {
Obj.wait ()
}
Obj.doSomething ()
}
When thread An acquires the obj lock, it finds that the condition condition is not satisfied and cannot proceed to the next processing, so thread A wait ().
In another thread B, if B changes some conditions so that the condition condition of thread An is met, thread A can be awakened:
Synchronized (obj) {
Condition = true
Obj.notify ()
}
The concepts that need to be noted are:
# before calling the wait () and notify () methods of obj, you must obtain the obj lock, that is, you must write it in the synchronized (obj) {...} code segment.
# after calling obj.wait (), thread A releases the lock of obj, otherwise thread B cannot acquire the obj lock and cannot wake up An in the synchronized (obj) {...} code segment.
# when the obj.wait () method returns, thread A needs to acquire the obj lock again before it can continue execution.
# if A1 Magic A2 Magi A3 are all in obj.wait (), then B calls obj.notify () to awaken only one of A1 Magic A2 Magic A3 (which one is decided by JVM).
# obj.notifyAll () can all wake up A1 Magi A2 Magi A3, but to continue to execute the next statement of obj.wait (), you must obtain an obj lock. Therefore, only one of A1 Magi A2 Magi A3 has a chance to acquire a lock to continue execution, such as A1. The rest need to wait for A1 to release the obj lock before continuing execution.
# when B calls obj.notify/notifyAll, B is holding the obj lock. Therefore, although A1 Magi A2 Magi A3 is awakened, it is still unable to obtain the obj lock. It is not until B exits the synchronized block and releases the obj lock that one of the A1 Magi A2 Magi A3 has a chance to acquire the lock to continue execution.
Talk about the relationship between synchronized and wait (), notify (), etc.
1. Where there is synchronized, there is not necessarily wait,notify.
two。 Where there is wait,notify, there must be synchronized. This is because wait and notify are not threaded classes, but methods that every object has, and both methods are related to object locks, where there are locks, there must be synchronized.
In addition, note that if you want to use the notify and wait methods together, you must first call notify and then call wait, because if you finish calling wait, the thread is no longer currentthread.
Using wait and notify to implement producers and consumers
1. Matters needing attention
Always use wait, notify, and notifyAll in synchronized functions or objects, otherwise the Java virtual machine generates IllegalMonitorStateException.
Always use wait in the while loop rather than under the if statement. In this way, the loop checks the condition of the wait before and after the thread sleeps and processes the wake-up notification if the condition has not actually changed.
Always use wait on objects that are shared between multiple threads.
Notify randomly notifies a thread blocking on the object; notifyAll notifies all threads blocking on the object.
two。 Code example
2.1 producer
Public class Producer implements Runnable {
Private Queue queue
Private int maxSize
Public Producer (Queue queue, int maxSize) {
This.queue = queue
This.maxSize = maxSize
}
@ Override
Public void run () {
While (true) {
Synchronized (queue) {
While (queue.size ()) = = maxSize) {
Try {
System.out.println ("Queue is Full")
Queue.wait ()
} catch (InterruptedException ie) {
Ie.printStackTrace ()
}
}
Random random = new Random ()
Int I = random.nextInt ()
System.out.println ("Produce" + I)
Queue.add (I)
Queue.notifyAll ()
}
}
}
}
2.2 consumers
Public class Consumer implements Runnable {
Private Queue queue
Private int maxSize
Public Consumer (Queue queue, int maxSize) {
This.queue = queue
This.maxSize = maxSize
}
@ Override
Public void run () {
While (true) {
Synchronized (queue) {
While (queue.isEmpty ()) {
System.out.println ("Queue is Empty")
Try {
Queue.wait ()
} catch (InterruptedException ie) {
Ie.printStackTrace ()
}
}
Int v = queue.remove ()
System.out.println ("Consume" + v)
Queue.notifyAll ()
}
}
}
}
2.3 Main
Public class Main {
Public static void main (String [] args) {
Queue queue = new LinkedList ()
Int maxSize = 10
Producer p = new Producer (queue, maxSize)
Consumer c = new Consumer (queue, maxSize)
Thread pT = new Thread (p)
Thread pC = new Thread (c)
PT.start ()
PC.start ()
}
}
The above is the example analysis of wait and notify and consumer producers shared by Xiaobian. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.