Java thread — production and consumption

/* JDK1. Version 4: producer, consumer. The problem of multiple producers and consumers. If judgment flag, only once, will cause the thread that should not run to run. A data error occurred. The while judgment flag solves whether to run after the thread obtains the execution right! Notify: only one thread can be awakened. If our party wakes up our party, it is meaningless. Moreover, the while judgment Flag + notify will cause deadlock. NotifyAll solves the problem that our thread must wake up the other thread.

Although this method is feasible, its efficiency is not the best, jdk1 Version 4 can no longer solve the efficiency problem, and jdk1 is required 5 version can be solved*/

-------------------------------------------------------------------------------------------------------------------------- /* jdk1. After 5, the synchronization and lock are encapsulated into objects. The implicit mode of operation lock is defined into the object, and the implicit action is changed into a display action. Lock interface: the synchronization code block or synchronization function is replaced. Turn the synchronous implicit lock operation into a real lock operation. At the same time, it is more flexible. Multiple groups of monitors can be added to one lock. Lock(): get lock. Unlock (): to release a lock, you usually need to define it in a finally code block. Condition interface: the wait notify notifyAll method in object is replaced. These monitor methods are encapsulated separately into condition monitor objects. Any lock can be combined. await(); signal(); signalAll();

This version can improve efficiency because we don't have to wake up all objects and make redundant judgments;

Of course, we can specify the object wake-up. After the producer completes production, we only need to wake up the objects in the consumer; On the contrary, after consumers consume, we only need to specify wake-up producers.

Therefore, our efficiency has been improved because there is no need to make redundant judgments*/

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