Regarding producers and consumer pattern in java with blocking queue approach

前端 未结 3 1539
小鲜肉
小鲜肉 2021-01-03 16:41

I was doing a research in producers and consumer design patterns with regards to threads in java, I recently explored in java 5 with the introduction With introduction of Bl

3条回答
  •  粉色の甜心
    2021-01-03 17:07

    If you want to understand how a BlockingQueue works, for educational purposes, you can always have a look on its source code.

    The simplest way could be to synchronize the offer() and take() methods, and once the queue is full and someone is trying to offer() an element - invoke wait(). When someone is taking an element, notify() the sleeping thread. (Same idea when trying to take() from an empty queue).
    Remember to make sure all your wait() calls are nested in loops that checks if the conditions are met each time the thread is awakened.

    If you are planning to implement it from scratch for product purposes - I'd strongly argue against it. You should use an existing, tested libraries and components as much as possible.

提交回复
热议问题