Java implementation method producers and consumers

Producer and consumer problem is a classic problem of threading model:
producers and consumers share the same memory space in the same period, the producer added to the storage space products, consumer products removed from the storage space.
When storage space is empty, consumers obstruction, when storage space is full, the producer blocked.

Implementation (part) are:

1. Use wait () method, and notify () method implementation. This is the simplest and most basic implementation, the buffer is full and empty buffers are calling wait () method to wait, when producers to produce a product or a product after consumer spending will wake up all threads.

2. reentrant lock of ReentrantLock achieved. Reentrant lock, also known as recursive locks, referring to the same thread after the outer function to obtain a lock, the inner recursive functions still have to acquire the lock code, but will not be affected, in simple terms, which maintains a lock and access lock-related counters, if you have a thread lock lock once again, the acquisition counter is incremented, the end of the function call counter decrements, then lock to be released twice to get a real release. Already acquired a lock thread into the other synchronized block requires the same lock it will not be blocked.

3. BlockingQueue blocking queue implementation. BlockingQueue that is blocking queue, it can be seen from the blocking of the word, and in some cases blocked access to the queue may cause blocking. There are cases blocked major following two:

3.1. When the queue is full when carried into queues

3.2 .. When the queue time for an empty queue operation

Therefore, when a thread is full of blocking queue enqueue operation will be blocked, unless there is another thread was a team operation; when a thread is blocked on an empty queue dequeue operation will be blocked, unless there was another thread enqueue operation. Therefore, blocking queue is thread-safe.

发布了62 篇原创文章 · 获赞 34 · 访问量 4万+

Guess you like

Origin blog.csdn.net/qq_42451835/article/details/104221278