Consolidation of java thread foundation --- producer-consumer model under multi-threading, and a detailed introduction to the notifyAll method

In the last time [ http://www.cnblogs.com/webor2006/p/8419565.html ], I demonstrated the situation of multiple products and multiple consumers suspended animation, this time to solve the suspended animation to achieve a real multi-threaded producer Consumer model, look at the official documents of wait() and notify() before solving, because the reason for suspended animation is related to these two methods:

Among them, 0 means waiting forever. If you pass a parameter greater than 0 to wait, it means that wait will not wait after the specified time, so you can continue to read the official comment of wait():

This sentence mentions a key point: calling the wait() method actually releases the ownership of the listener, and when it is awakened, it cannot be executed immediately, but the code below it will be executed after the direct acquisition is successful. . For the thread that has been wait(), it needs to be woken up by notify() or notifyAll(), and notify() is to notify a thread to wake up, and notifyAll() will wait() in all threads of the same monitor will wake up, and to solve the previous deadlock of multiple producers and consumers, the notifyAll() method has to be used. Let's use it to transform the deadlocked program:

 

6-40

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324653029&siteId=291194637