多线程环境下,我们经常需要多个线程的并发和协作。这个时候,就需要了解一个重要的多线程并发协作模型“生产者/消费者模式”。
生产者:
生产者指的是负责生产数据的模块(这里模块可能是:方法、对象、线程、进程)。
消费者:
消费者指的是负责处理数据的模块(这里模块可能是:方法、对象、线程、进程)。
缓冲区:
消费者不能直接使用生产者的数据,它们之间有个“缓冲区”。生产者将生产好的数据放入“缓冲区”,消费者从“缓冲区”拿要处理的数据。
![](https://img-blog.csdnimg.cn/20201003233636254.png)
缓冲区是实现并发的核心,缓冲区的设置有3个好处:
实现线程的并发协作
有了缓冲区以后,生产者线程只需要往缓冲区里面放置数据,而不需要管消费者消费的情况;同样,消费者只需要从缓冲区拿数据处理即可,也不需要管生产者生产的情况。 这样,就从逻辑上实现了“生产者线程”和“消费者线程”的分离。
解耦了生产者和消费者
生产者不需要和消费者直接打交道。
解决忙闲不均,提高效率
生产者生产数据慢时,缓冲区仍有数据,不影响消费者消费;消费者处理数据慢时,生产者仍然可以继续往缓冲区里面放置数据 。
网购平台的高并发,就是一种生产者消费者模型
科普一下网购平台专业词汇:
PV:page view,页面访问量
UV:unique view,用户ID一次登录记一次
VV:visist view,访问量登录到退出算一次
线程通信 1
-
信号灯法
-
管程法
线程通信的常用方法 2
Modifier and Type Method | Description |
---|---|
void notify() | Wakes up a single thread that is waiting on this object’s monitor. |
void notifyAll() | Wakes up all threads that are waiting on this object’s monitor. |
String toString() | Returns a string representation of the object. |
void wait() | Causes the current thread to wait until it is awakened, typically by being notified or interrupted. |
void wait(long timeoutMillis) | Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed. |